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

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

Introduction

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

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:net.morphbank.webclient.RemoteImageProcessing.java

public void sendImage(String strURL, String id, String originalFileName, String imageFileName)
        throws Exception {
    File input = new File(imageFileName);
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);

    Part[] parts = { new StringPart("id", id), new StringPart("fileName", originalFileName),
            new FilePart("image", originalFileName, input) };
    RequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
    post.setRequestEntity(entity);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {//from   w ww  .ja v  a 2s.  com
        System.out.println("Trying post");
        int postStatus = httpclient.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + postStatus);
        // Display response
        System.out.print("Response body: ");
        InputStream response = post.getResponseBodyAsStream();
        for (int i = response.read(); i != -1; i = response.read()) {
            System.out.write(i);
        }
        System.out.flush();
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
}

From source file:jp.primecloud.auto.zabbix.ZabbixAccessor.java

protected String post(String jsonRequest) {
    PostMethod postMethod = new PostMethod(apiUrl);
    postMethod.setRequestHeader("Content-Type", "application/json-rpc");
    postMethod.setRequestEntity(new ByteArrayRequestEntity(jsonRequest.getBytes()));

    int status;/*from   w w w  .j  a  va2 s . c  o  m*/
    try {
        status = httpClient.executeMethod(postMethod);
    } catch (HttpException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (status < 200 || status >= 300) {
        String body;
        try {
            body = postMethod.getResponseBodyAsString();
        } catch (Exception ignore) {
            body = "";
        }
        throw new RuntimeException("Reponse Error: status=" + status + ", body=" + body);
    }

    String jsonResponse;
    try {
        jsonResponse = postMethod.getResponseBodyAsString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return jsonResponse;
}

From source file:com.mindquarry.common.index.SolrIndexClient.java

private void sendToIndexer(byte[] content) throws Exception {
    PostMethod pMethod = new PostMethod(solrEndpoint);
    pMethod.setDoAuthentication(true);/*ww w .j a  v a 2  s  . c  o m*/
    pMethod.addRequestHeader("accept", "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$
    pMethod.setRequestEntity(new ByteArrayRequestEntity(content));

    try {
        httpClient.executeMethod(pMethod);
    } finally {
        pMethod.releaseConnection();
    }

    if (pMethod.getStatusCode() == 200) {
        // everything worked fine, nothing more to do
    } else if (pMethod.getStatusCode() == 401) {
        getLogger().warn("Authorization problem. Could not connect to index updater.");
    } else {
        System.out.println("Unknown error");
        System.out.println("STATUS: " + pMethod.getStatusCode());
        System.out.println("RESPONSE: " + pMethod.getResponseBodyAsString());
    }
    pMethod.releaseConnection();
}

From source file:edu.usc.corral.api.Client.java

public <T> T doPost(String path, Class<? extends T> responseType, Object request) throws GlideinException {
    ensureOpen();/*from  w w w .ja v  a 2s .c  o  m*/

    Serializer serializer = new Persister();
    RequestEntity entity = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        serializer.write(request, baos);
        entity = new ByteArrayRequestEntity(baos.toByteArray(), "text/xml");
    } catch (Exception e) {
        throw new GlideinException("Unable to generate request xml", e);
    }

    PostMethod post = new PostMethod(path);
    try {
        post.setRequestEntity(entity);
        int status = httpclient.executeMethod(post);
        InputStream is = post.getResponseBodyAsStream();
        if (status < 200 || status > 299) {
            handleError(is);
        }
        return serializer.read(responseType, is);
    } catch (HttpException he) {
        throw new GlideinException("Error parsing http", he);
    } catch (IOException ioe) {
        throw new GlideinException("Error communicating with server", ioe);
    } catch (GlideinException ge) {
        throw ge;
    } catch (Exception e) {
        throw new GlideinException("Unable to parse response xml", e);
    } finally {
        post.releaseConnection();
    }
}

From source file:edu.caltech.ipac.firefly.server.util.multipart.MultiPartPostBuilder.java

/**
 * Post this multipart request.//from   ww w .j av  a  2  s.  c o m
 * @param responseBody  the response is written into this OutputStream.
 * @return a MultiPartRespnse which contains headers, status, and status code.
 */
public MultiPartRespnse post(OutputStream responseBody) {

    if (targetURL == null || parts.size() == 0) {
        return null;
    }

    logStart();

    PostMethod filePost = new PostMethod(targetURL);

    for (Param p : headers) {
        filePost.addRequestHeader(p.getName(), p.getValue());
    }

    try {

        filePost.setRequestEntity(
                new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), filePost.getParams()));

        HttpServices.executeMethod(filePost, userId, passwd);

        MultiPartRespnse resp = new MultiPartRespnse(filePost.getResponseHeaders(), filePost.getStatusCode(),
                filePost.getStatusText());
        if (responseBody != null) {
            readBody(responseBody, filePost.getResponseBodyAsStream());
        }
        return resp;

    } catch (Exception ex) {
        LOG.error(ex, "Error while posting multipart request to" + targetURL);
        return null;
    } finally {
        filePost.releaseConnection();
    }
}

From source file:com.zimbra.qa.unittest.TestUserServlet.java

/** Bug 84362 Confirm that import with London timezone incorrectly identified as "GMT" works */
public void testIcsImportExportGMTtoLondon() throws IOException, ServiceException {
    ZMailbox mbox = TestUtil.getZMailbox(USER_NAME);
    String calName = NAME_PREFIX + "3rdCalendar";
    String calUri = String.format("/%s?fmt=ics", calName);
    TestUtil.createFolder(mbox, calName, ZFolder.View.appointment);
    URI uri = mbox.getRestURI(calUri);
    HttpClient client = mbox.getHttpClient(uri);
    PostMethod post = new PostMethod(uri.toString());
    post.setRequestEntity(new InputStreamRequestEntity(
            new ByteArrayInputStream(TestCalDav.LOTUS_NOTES_WITH_BAD_GMT_TZID.getBytes()),
            MimeConstants.CT_TEXT_CALENDAR));
    ZimbraLog.test.debug("testIcsImportExport:ICS to be imported:%s", TestCalDav.LOTUS_NOTES_WITH_BAD_GMT_TZID);
    TestCalDav.HttpMethodExecutor.execute(client, post, HttpStatus.SC_OK);
    uri = mbox.getRestURI(calUri);/*  w ww. j av  a2s.  c  om*/
    GetMethod get = new GetMethod(uri.toString());
    TestCalDav.HttpMethodExecutor executor = new TestCalDav.HttpMethodExecutor(client, get, HttpStatus.SC_OK);
    String respIcal = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    ZimbraLog.test.debug("testIcsImportExport:ICS exported:%s", respIcal);
    // If this is present, it implies that both the timezone and the references have been correctly changed.
    String dtstartWithNewTZID = "DTSTART;TZID=\"Europe/London\":20150721T140000";
    int dtstartIndex = respIcal.indexOf(dtstartWithNewTZID);
    assertTrue(String.format("'%s' should be present", dtstartWithNewTZID), -1 != dtstartIndex);
}

From source file:com.predic8.membrane.interceptor.LoadBalancingInterceptorTest.java

private PostMethod getPostMethod() {
    PostMethod post = new PostMethod("http://localhost:7000/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  w  ww. ja  v a  2  s .c  o  m
}

From source file:com.predic8.membrane.integration.Http10Test.java

@Test
public void testPost() throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);

    PostMethod post = new PostMethod("http://localhost:3000/axis2/services/BLZService");
    InputStream stream = this.getClass().getResourceAsStream("/getBank.xml");

    InputStreamRequestEntity entity = new InputStreamRequestEntity(stream);
    post.setRequestEntity(entity);
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "\"\"");
    int status = client.executeMethod(post);
    assertEquals(200, status);/*from  ww  w . ja  v  a  2  s .c  o m*/
    assertEquals("HTTP/1.1", post.getStatusLine().getHttpVersion());

    String response = post.getResponseBodyAsString();
    assertNotNull(response);
    assertTrue(response.length() > 0);
}

From source file:com.predic8.membrane.integration.Http11Test.java

private void testPost(boolean useExpect100Continue) throws Exception {
    HttpClient client = new HttpClient();
    if (useExpect100Continue)
        initExpect100ContinueWithFastFail(client);
    PostMethod post = new PostMethod("http://localhost:4000/axis2/services/BLZService");
    InputStream stream = this.getClass().getResourceAsStream("/getBank.xml");

    InputStreamRequestEntity entity = new InputStreamRequestEntity(stream);
    post.setRequestEntity(entity);
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "");

    int status = client.executeMethod(post); // also see comment on initExpect100ContinueWithFastFail()
    assertEquals(200, status);//www  .  ja  v  a  2s .com
    assertNotNull(post.getResponseBodyAsString());
    assertFalse(isNullOrEmpty(post.getResponseBodyAsString()));
    //System.out.println(post.getResponseBodyAsString());
}

From source file:com.arc.embeddedcdt.gui.jtag.ConfigJTAGTab.java

static private String executeCommandTcl(String ip, String command, File f) {
    PostMethod filePost = new PostMethod("http://" + ip + "/ram/cgi/execute.tcl");

    try {//from  ww  w. j  a  v a2 s . co  m
        //         filePost.getParams().setBooleanParameter(
        //               HttpMethodParams.USE_EXPECT_CONTINUE, true);

        Part[] parts;
        if (f != null) {
            parts = new Part[] { new StringPart("form_command", command),
                    new FilePart("form_filecontent", "file", f) };
        } else {
            parts = new Part[] { new StringPart("form_command", command) };
        }
        MultipartRequestEntity re = new MultipartRequestEntity(parts, filePost.getParams());
        filePost.setRequestEntity(re);
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            String result = filePost.getResponseBodyAsString();

            Pattern p = Pattern.compile("(?s)Error: ([0-9]+)\n.*");
            Matcher m = p.matcher(result);
            if (!m.matches()) {
                throw new RuntimeException("Unknown result from execute.tcl: " + result);
            }
            Integer errorCode = Integer.parseInt(m.group(1));
            if (errorCode != 0) {
                throw new RuntimeException("Command \"" + command + "\" failed with error code " + errorCode);
            }
            p = Pattern.compile("(?s)Error: [0-9]+\n(.*)");
            m = p.matcher(result);
            if (!m.matches()) {
                throw new RuntimeException("Unknown result from execute.tcl: " + result);
            }
            return m.group(1);

        } else {
            throw new RuntimeException("Upload failed");
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (HttpException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        filePost.releaseConnection();
    }
}