Example usage for org.apache.commons.httpclient.methods PostMethod PostMethod

List of usage examples for org.apache.commons.httpclient.methods PostMethod PostMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod PostMethod.

Prototype

public PostMethod(String paramString) 

Source Link

Usage

From source file:com.mercatis.lighthouse3.commons.commons.HttpRequest.java

/**
 * This method performs a file upload via multipart POST request.
 *
 * @param url            the URL against which the file upload is performed
 * @param file           the file to upload
 * @param postParameters any additional parameters to add to the POST request
 * @return the data returned by the web server
 * @throws HttpException in case a communication error occurred.
 *//*from ww  w. j av a2  s . c o m*/
public String postFileUpload(String url, File file, Map<String, String> postParameters) {

    PostMethod filePost = null;

    try {
        filePost = new PostMethod(url);
        Part[] mimeParts = new Part[postParameters.size() + 1];
        mimeParts[0] = new FilePart(file.getName(), file);
        int p = 1;
        for (String parameterName : postParameters.keySet()) {
            mimeParts[p] = new StringPart(parameterName, postParameters.get(parameterName));
            p++;
        }

        filePost.setRequestEntity(new MultipartRequestEntity(mimeParts, filePost.getParams()));
    } catch (Exception anyProblem) {
        throw new HttpException("A problem occurred while constructing file upload request", anyProblem);
    }

    int resultCode = 0;
    String resultBody = null;

    try {
        resultCode = this.httpClient.executeMethod(filePost);
        resultBody = filePost.getResponseBodyAsString();

        if (resultCode != 200) {
            throw new HttpException(resultBody, null);
        }
    } catch (HttpException httpException) {
        throw new HttpException("HTTP file upload failed", httpException);
    } catch (IOException ioException) {
        throw new HttpException("HTTP file upload failed", ioException);
    } finally {
        filePost.releaseConnection();
    }

    return resultBody;
}

From source file:com.intranet.intr.sms.EmpControllerSms.java

@RequestMapping(value = "ESMS.htm", method = RequestMethod.POST)
public String addEstudio_post(@ModelAttribute("mensaje") sms mensaje, BindingResult result, ModelMap map) {
    try {/*from w  w w  . j a v  a2  s.  c om*/
        map.addAttribute("msg", "success");
        HttpClient client = new HttpClient();
        client.setStrictMode(true);
        //Se fija el tiempo maximo de espera de la respuesta del servidor
        client.setTimeout(60000);
        //Se fija el tiempo maximo de espera para conectar con el servidor
        client.setConnectionTimeout(5000);
        PostMethod post = null;
        //Se fija la URL sobre la que enviar la peticion POST
        //Como ejemplo la peticion se enva a www.altiria.net/sustituirPOSTsms
        //Se debe reemplazar la cadena /sustituirPOSTsms por la parte correspondiente
        //de la URL suministrada por Altiria al dar de alta el servicio
        post = new PostMethod("http://www.altiria.net/api/http");
        //Se fija la codificacion de caracteres en la cabecera de la peticion
        post.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        //Se crea la lista de parametros a enviar en la peticion POST
        NameValuePair[] parametersList = new NameValuePair[6];
        //XX, YY y ZZ se corresponden con los valores de identificacion del
        //usuario en el sistema.
        parametersList[0] = new NameValuePair("cmd", "sendsms");
        parametersList[1] = new NameValuePair("domainId", "comercial");
        parametersList[2] = new NameValuePair("login", "jfruano");
        parametersList[3] = new NameValuePair("passwd", "wrnkmekt");
        parametersList[4] = new NameValuePair("dest", "34" + mensaje.getNum());
        parametersList[5] = new NameValuePair("msg", "" + mensaje.getTexto());
        //Se rellena el cuerpo de la peticion POST con los parametros
        post.setRequestBody(parametersList);
        int httpstatus = 0;
        String response = null;
        try {
            //Se enva la peticion
            httpstatus = client.executeMethod(post);
            //Se consigue la respuesta
            response = post.getResponseBodyAsString();
        } catch (Exception e) {
            //Habra que prever la captura de excepciones

        } finally {
            //En cualquier caso se cierra la conexion
            post.releaseConnection();
        }
        //Habra que prever posibles errores en la respuesta del servidor
        if (httpstatus != 200) {

        } else {
            //Se procesa la respuesta capturada en la cadena response
        }
    } catch (Exception ex) {
        ex.printStackTrace();

    }
    return "redirect:ESMS.htm";

}

From source file:com.kylinolap.jdbc.stub.KylinClient.java

@Override
public void connect() throws ConnectionException {
    PostMethod post = new PostMethod(conn.getConnectUrl());
    HttpClient httpClient = new HttpClient();

    if (conn.getConnectUrl().toLowerCase().startsWith("https://")) {
        registerSsl();/*ww w.j  a va2s  .c o  m*/
    }
    addPostHeaders(post);

    try {
        StringRequestEntity requestEntity = new StringRequestEntity("{}", "application/json", "UTF-8");
        post.setRequestEntity(requestEntity);
        httpClient.executeMethod(post);

        if (post.getStatusCode() != 200 && post.getStatusCode() != 201) {
            logger.error("Authentication Failed with error code " + post.getStatusCode() + " and message:\n"
                    + post.getResponseBodyAsString());

            throw new ConnectionException("Authentication Failed.");
        }
    } catch (HttpException e) {
        logger.error(e.getLocalizedMessage(), e);
        throw new ConnectionException(e.getLocalizedMessage());
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage(), e);
        throw new ConnectionException(e.getLocalizedMessage());
    }
}

From source file:com.ohalo.baidu.map.BaiduMapTest.java

/**
 * /*from   w ww .j a va 2s.  c om*/
 * <pre>
 * ??
 * 
 * 2013-10-8
 * </pre>
 * 
 * @throws IllegalArgumentException
 * @throws IOException
 */
public void testSearchCompanyBaseInfo() throws IllegalArgumentException, IOException {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod("http://www.sgs.gov.cn/lz/etpsInfo.do?method=doSearch");
    method.setRequestBody(new NameValuePair[] {
            new NameValuePair("keyWords",
                    new String("??".getBytes(), "ISO8859-1")),
            new NameValuePair("searchType", "1") });
    client.executeMethod(method);
    String response = new String(method.getResponseBody());
    System.out.println(response);
}

From source file:net.jadler.JadlerMockingIntegrationTest.java

@Test
public void havingBody() throws Exception {
    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new StringRequestEntity("postbody", null, null));

    this.client.executeMethod(method);

    verifyThatRequest().havingBodyEqualTo("postbody").havingBody(notNullValue())
            .havingBody(not(isEmptyOrNullString())).receivedOnce();
}

From source file:com.intranet.intr.sms.SupControllerSms.java

@RequestMapping(value = "SMS.htm", method = RequestMethod.POST)
public String addEstudio_post(@ModelAttribute("mensaje") sms mensaje, BindingResult result, ModelMap map) {
    //String mensaje="";
    try {/*from   ww  w  . ja va  2  s .  c o m*/
        map.addAttribute("msg", "success");
        HttpClient client = new HttpClient();
        client.setStrictMode(true);
        //Se fija el tiempo maximo de espera de la respuesta del servidor
        client.setTimeout(60000);
        //Se fija el tiempo maximo de espera para conectar con el servidor
        client.setConnectionTimeout(5000);
        PostMethod post = null;
        //Se fija la URL sobre la que enviar la peticion POST
        //Como ejemplo la peticion se enva a www.altiria.net/sustituirPOSTsms
        //Se debe reemplazar la cadena /sustituirPOSTsms por la parte correspondiente
        //de la URL suministrada por Altiria al dar de alta el servicio
        post = new PostMethod("http://www.altiria.net/api/http");
        //Se fija la codificacion de caracteres en la cabecera de la peticion
        post.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        //Se crea la lista de parametros a enviar en la peticion POST
        NameValuePair[] parametersList = new NameValuePair[6];
        //XX, YY y ZZ se corresponden con los valores de identificacion del
        //usuario en el sistema.
        parametersList[0] = new NameValuePair("cmd", "sendsms");
        parametersList[1] = new NameValuePair("domainId", "comercial");
        parametersList[2] = new NameValuePair("login", "jfruano");
        parametersList[3] = new NameValuePair("passwd", "wrnkmekt");
        parametersList[4] = new NameValuePair("dest", "34" + mensaje.getNum());
        parametersList[5] = new NameValuePair("msg", "" + mensaje.getTexto());
        //Se rellena el cuerpo de la peticion POST con los parametros
        post.setRequestBody(parametersList);
        int httpstatus = 0;
        String response = null;
        try {
            //Se enva la peticion
            httpstatus = client.executeMethod(post);
            //Se consigue la respuesta
            response = post.getResponseBodyAsString();
        } catch (Exception e) {
            //Habra que prever la captura de excepciones

        } finally {
            //En cualquier caso se cierra la conexion
            post.releaseConnection();
        }
        //Habra que prever posibles errores en la respuesta del servidor
        if (httpstatus != 200) {

        } else {
            //Se procesa la respuesta capturada en la cadena response
        }
    } catch (Exception ex) {
        ex.printStackTrace();

    }
    return "redirect:SMS.htm";

}

From source file:fi.solita.phantomrunner.browserserver.HttpPhantomJsServerNotifier.java

private JsonNode send(Map<String, Object> jsonMap) {
    try {/*w  w  w.j a  v a 2  s.com*/
        // FIXME: should relly get this port from the JUnit configs but have no real way to pass this
        //        to JavaScript side of things yet, bummer
        PostMethod method = new PostMethod("http://localhost:18080");
        method.setRequestEntity(
                new StringRequestEntity(mapper.writeValueAsString(jsonMap), "application/json", "UTF-8"));

        int responseCode = client.executeMethod(method);

        switch (responseCode) {
        case HttpServletResponse.SC_INTERNAL_SERVER_ERROR:
            throw new RuntimeException("Internal server error occured: " + method.getResponseBodyAsString());
        default:
            return mapper.readTree(method.getResponseBodyAsString());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:fr.opensagres.xdocreport.remoting.reporting.server.ReportingServiceWithHttpClientTestCase.java

@Test
public void generateReport() throws Exception {

    PostMethod post = new PostMethod("http://localhost:" + PORT + "/report");

    String ct = "multipart/mixed";
    post.setRequestHeader("Content-Type", ct);
    Part[] parts = new Part[6];
    String fileName = "DocxProjectWithVelocityAndImageList.docx";

    // 1) Param [templateDocument]: input stream of the docx, odt...
    parts[0] = new FilePart("templateDocument", new File(root, fileName),
            "application/vnd.oasis.opendocument.text", "UTF-8");

    // 2) Param [templateEngineKind]: Velocity or Freemarker
    parts[1] = new StringPart("templateEngineKind", "Velocity");

    // 3) Param [metadata]: XML fields metadata
    // XML fields metadata
    // ex:<?xml version="1.0" encoding="UTF-8" standalone="yes"?><fields templateEngineKind=""
    // ><description><![CDATA[]]></description><field name="developers.Name" list="true" imageName=""
    // syntaxKind=""><description><![CDATA[]]></description></field><field name="developers.LastName" list="true"
    // imageName="" syntaxKind=""><description><![CDATA[]]></description></field><field name="developers.Mail"
    // list="true" imageName="" syntaxKind=""><description><![CDATA[]]></description></field></fields>
    FieldsMetadata metadata = new FieldsMetadata();

    // manage lazy loop for the table which display list of developers in the docx
    metadata.addFieldAsList("developers.Name");
    metadata.addFieldAsList("developers.LastName");
    metadata.addFieldAsList("developers.Mail");

    StringWriter xml = new StringWriter();
    metadata.saveXML(xml);/* w ww .  j  a  va2 s  .  co m*/
    parts[2] = new StringPart("metadata", xml.toString());

    // 4) Param [data]: JSON data which must be merged with the docx template
    String jsonData = "{" + "project:" + "{Name:'XDocReport', URL:'http://code.google.com/p/xdocreport'}, "
            + "developers:" + "[" + "{Name: 'ZERR', Mail: 'angelo.zerr@gmail.com',LastName: 'Angelo'},"
            + "{Name: 'Leclercq', Mail: 'pascal.leclercq@gmail.com',LastName: 'Pascal'}" + "]" + "}";
    parts[3] = new StringPart("data", jsonData);

    // 4) Param [dataType]: data type
    parts[4] = new StringPart("dataType", "json");
    // 5) Param [outFileName]: output file name
    parts[5] = new StringPart("outFileName", "report.docx");
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(post);
        Assert.assertEquals(200, result);
        Assert.assertEquals("attachment; filename=\"report.docx\"",
                post.getResponseHeader("Content-Disposition").getValue());

        byte[] convertedDocument = post.getResponseBody();
        Assert.assertNotNull(convertedDocument);

        File outFile = new File("target/report.docx");
        outFile.getParentFile().mkdirs();
        IOUtils.copy(new ByteArrayInputStream(convertedDocument), new FileOutputStream(outFile));

    } finally {

        post.releaseConnection();
    }
}

From source file:fr.msch.wissl.server.TestIndexer.java

public void test() throws Exception {
    HttpClient client = new HttpClient();

    // /indexer/status as user: 401
    GetMethod get = new GetMethod(URL + "indexer/status");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);/*from   ww  w  . j  a v a 2s .c o  m*/
    Assert.assertEquals(401, get.getStatusCode());

    // /indexer/status as admin: 200
    get = new GetMethod(URL + "indexer/status");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    JSONObject obj = new JSONObject(get.getResponseBodyAsString());
    // won't try to check the actual content of this object,
    // since I can't predict easily and accurately if 
    // the Indexer will be in Running or Sleeping state at a given time.
    assertTrue(obj.has("running"));
    assertTrue(obj.has("percentDone"));
    assertTrue(obj.has("secondsLeft"));
    assertTrue(obj.has("songsDone"));
    assertTrue(obj.has("songsTodo"));

    // /indexer/rescan as user: 401
    PostMethod post = new PostMethod(URL + "indexer/rescan");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // /indexer/rescan as amdin
    post = new PostMethod(URL + "indexer/rescan");
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(204, post.getStatusCode());

    // /folders as user: 401
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(401, get.getStatusCode());

    // /folders: should be empty
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(0, obj.getJSONArray("folders").length());

    // /folders/listing as user: 401
    get = new GetMethod(URL + "folders/listing");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(401, get.getStatusCode());

    // /folders/listing on some file that does not exist: 404
    get = new GetMethod(URL + "folders/listing?directory=/does/not/exist");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(404, get.getStatusCode());

    File exp_home = new File(System.getProperty("user.home"));

    // /folders/listing with no arg: homedir
    get = new GetMethod(URL + "folders/listing");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(File.separator, obj.getString("separator"));
    File dir = new File(obj.getString("directory"));
    assertEquals(exp_home.getAbsolutePath(), dir.getAbsolutePath());
    assertEquals(exp_home.getParentFile().getAbsolutePath(), dir.getParentFile().getAbsolutePath());
    assertTrue(obj.getJSONArray("listing").length() > 0);

    // /folders/listing with arg '$ROOT'
    get = new GetMethod(URL + "folders/listing?directory=$ROOT");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    Assert.assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(File.separator, obj.getString("separator"));
    File[] dirs = File.listRoots();
    assertEquals("", obj.getString("directory"));
    assertEquals("$ROOT", obj.getString("parent"));
    JSONArray arr = obj.getJSONArray("listing");
    HashSet<String> hs = new HashSet<String>(arr.length());
    for (int i = 0; i < arr.length(); i++) {
        hs.add(new File(arr.getString(i)).getAbsolutePath());
    }
    for (File d : dirs) {
        // on windows, listRoots returns a bunch of drive names that don't exist
        if (d.exists()) {
            assertTrue(hs.remove(d.getAbsolutePath()));
        }
    }
    assertTrue(hs.isEmpty());

    // lists test resources folder
    File f = new File("src/test/resources/data2");
    get = new GetMethod(URL + "folders/listing?directory=" + URIUtil.encodeQuery(f.getAbsolutePath()));
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(File.separator, obj.getString("separator"));
    dir = new File(obj.getString("directory"));
    assertEquals(f.getAbsolutePath(), dir.getAbsolutePath());
    assertEquals(f.getParentFile().getAbsolutePath(), dir.getParentFile().getAbsolutePath());
    dirs = dir.listFiles();
    arr = obj.getJSONArray("listing");
    assertEquals(2, arr.length());
    assertEquals(new File("src/test/resources/data2/sub1").getAbsolutePath(), arr.get(0));
    assertEquals(new File("src/test/resources/data2/sub2").getAbsolutePath(), arr.get(1));

    // /folders/add as user: 401
    post = new PostMethod(URL + "folders/add");
    post.addParameter("directory", "/");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // /folders/add : directory does not exist: 404
    post = new PostMethod(URL + "folders/add");
    post.addParameter("directory", "/does/not/exist");
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(404, post.getStatusCode());

    // /folders/add : not a directory: 400
    post = new PostMethod(URL + "folders/add");
    post.addParameter("directory", new File("src/test/resources/data/1.mp3").getAbsolutePath());
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // /folders/add "/src/test/resources/data"
    f = new File("src/test/resources/data");
    RuntimeStats rt = new RuntimeStats();
    rt.songCount.set(15);
    rt.albumCount.set(5);
    rt.artistCount.set(2);
    rt.playlistCount.set(0);
    rt.userCount.set(2);
    rt.playtime.set(15);
    rt.downloaded.set(0);
    this.addMusicFolder(f.getAbsolutePath(), rt);

    // check /folders
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(f.getAbsolutePath(), obj.getJSONArray("folders").getString(0));

    // /folders/add "/src/test/resources/data2/sub1"
    f = new File("src/test/resources/data2/sub1");
    rt.songCount.addAndGet(3);
    rt.albumCount.addAndGet(1);
    rt.artistCount.addAndGet(1);
    rt.playtime.addAndGet(3);
    this.addMusicFolder(f.getAbsolutePath(), rt);

    // /folders/add "/src/test/resources/data2/"
    f = new File("src/test/resources/data2/");
    rt.songCount.addAndGet(6);
    rt.playtime.addAndGet(6);
    this.addMusicFolder(f.getAbsolutePath(), rt);

    // check /folders
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    arr = obj.getJSONArray("folders");
    assertEquals(3, arr.length());
    for (int i = 0; i < 3; i++) {
        String s = new File(arr.getString(i)).getAbsolutePath();
        String s1 = new File("src/test/resources/data").getAbsolutePath();
        String s2 = new File("src/test/resources/data2/sub1").getAbsolutePath();
        String s3 = new File("src/test/resources/data2").getAbsolutePath();
        assertTrue(s.equals(s1) || s.equals(s2) || s.equals(s3));
    }

    // /folders/remove as user: 401
    post = new PostMethod(URL + "folders/remove");
    post.addParameter("directory[]", "/");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(401, post.getStatusCode());

    // /folders/remove unknown dir: 400
    post = new PostMethod(URL + "folders/remove");
    post.addParameter("directory[]", "/does/not/exist");
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    Assert.assertEquals(400, post.getStatusCode());

    // /folders/remove "/src/test/resources/data","src/test/resources/data2"
    post = new PostMethod(URL + "folders/remove");
    f = new File("src/test/resources/data");
    post.addParameter("directory[]", f.getAbsolutePath());
    f = new File("src/test/resources/data2");
    post.addParameter("directory[]", f.getAbsolutePath());
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    assertEquals(204, post.getStatusCode());

    rt.songCount.set(3);
    rt.albumCount.set(1);
    rt.artistCount.set(1);
    rt.userCount.set(2);
    rt.playtime.set(3);
    rt.downloaded.set(0);
    this.checkStats(rt);

    // /folders/remove "/src/test/resources/data/sub1"
    post = new PostMethod(URL + "folders/remove");
    f = new File("src/test/resources/data2/sub1");
    post.addParameter("directory[]", f.getAbsolutePath());
    post.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(post);
    assertEquals(204, post.getStatusCode());

    rt.songCount.set(0);
    rt.albumCount.set(0);
    rt.artistCount.set(0);
    rt.userCount.set(2);
    rt.playtime.set(0);
    rt.downloaded.set(0);
    this.checkStats(rt);

    // /folders: should be empty
    get = new GetMethod(URL + "folders");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(0, obj.getJSONArray("folders").length());

}

From source file:com.predic8.membrane.core.transport.http.InterceptorInvocationTest.java

private PostMethod createPostMethod() {
    PostMethod post = new PostMethod("http://localhost:4000/axis2/services/BLZService");
    post.setRequestEntity(new InputStreamRequestEntity(this.getClass().getResourceAsStream("/getBank.xml")));
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "");
    return post;//from   ww w  .  j a va  2 s. c om
}