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:mercury.UploadController.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        try {//from w ww.j  av a 2s. c o m
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String targetUrl = Config.getConfigProperty(ConfigurationEnum.DIGITAL_MEDIA);
                    if (StringUtils.isBlank(targetUrl)) {
                        targetUrl = request.getRequestURL().toString();
                        targetUrl = targetUrl.substring(0, targetUrl.lastIndexOf('/'));
                    }
                    targetUrl += "/DigitalMediaController";
                    PostMethod filePost = new PostMethod(targetUrl);
                    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
                    UploadPartSource src = new UploadPartSource(item.getName(), item.getSize(),
                            item.getInputStream());
                    Part[] parts = new Part[1];
                    parts[0] = new FilePart(item.getName(), src, item.getContentType(), null);
                    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
                    HttpClient client = new HttpClient();
                    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                    int status = client.executeMethod(filePost);
                    if (status == HttpStatus.SC_OK) {
                        String data = filePost.getResponseBodyAsString();
                        JSONObject json = new JSONObject(data);
                        if (json.has("id")) {
                            JSONObject responseJson = new JSONObject();
                            responseJson.put("success", true);
                            responseJson.put("id", json.getString("id"));
                            responseJson.put("uri", targetUrl + "?id=" + json.getString("id"));
                            response.getWriter().write(responseJson.toString());
                        }
                    }
                    filePost.releaseConnection();
                    return;
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (JSONException je) {
            je.printStackTrace();
        }
    }
    response.getWriter().write("{success: false}");
}

From source file:com.cubeia.backoffice.operator.client.OperatorServiceClientHTTP.java

@Override
public void createOperator(OperatorDTO operator) {
    PostMethod method = new PostMethod(baseUrl + CREATE_OPERATOR);
    prepareMethod(method);/*w ww.  j  a v  a  2 s  . co m*/
    try {

        String data = serialize(operator);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the method.
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.hp.alm.ali.rest.client.AliRestClient.java

private PostMethod initPostMethod(String restEndPoint, String xml) {
    PostMethod post = new PostMethod(restEndPoint);
    post.setRequestEntity(createRequestEntity(InputData.create(xml)));
    post.addRequestHeader("Content-type", "application/xml");

    return post;//from w  w w  .j  a v a 2s .c o m
}

From source file:jp.co.atware.solr.geta.GETAssocComponent.java

/**
 * /* w w  w .  jav a 2 s .c o m*/
 * @param requestBody
 * @return
 * @throws IOException
 */
protected InputStream postGss3Request(HttpClient client, String requestBody) throws IOException {
    PostMethod post = new PostMethod(config.settings.gss3url);
    RequestEntity requestEntity = new StringRequestEntity(requestBody, "text/xml", "UTF-8");
    post.setRequestEntity(requestEntity);
    post.addRequestHeader("User-Agent", "SolrGETAssocPlugin");

    int state = client.executeMethod(post);
    if (state == 200) {
        return post.getResponseBodyAsStream();
    }
    throw new IOException(post.getStatusLine().toString());
}

From source file:com.inbravo.scribe.rest.service.crm.ms.auth.SOAPExecutor.java

/**
 * //  w w  w  .  j a va 2s. c  o  m
 * @param url
 * @param soapEnvelope
 * @return
 * @throws UnsupportedEncodingException
 */
public final String getSOAPResponse(final String url, final String soapEnvelope)
        throws UnsupportedEncodingException {

    /* Post the SOAP to MS CRM */
    final PostMethod postMethod = new PostMethod(url);
    postMethod.addRequestHeader("Content-Type", "application/soap+xml; charset=UTF-8");

    /* Create new HTTP client */
    final HttpClient httpclient = new HttpClient();
    RequestEntity entity = new StringRequestEntity(soapEnvelope, "application/x-www-form-urlencoded", null);

    postMethod.setRequestEntity(entity);
    try {

        try {
            if (logger.isDebugEnabled()) {
                logger.debug("----Inside execute url: " + postMethod.getURI());
            }

            final int result = httpclient.executeMethod(postMethod);

            if (logger.isDebugEnabled()) {
                logger.debug("----Inside execute response code: " + result);
            }
            return postMethod.getResponseBodyAsString();
        } catch (final Exception exception) {
            /* Send user error */
            throw new ScribeException(ScribeResponseCodes._1008 + "Problem in calling MS CRM URL: " + url);
        }
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
}

From source file:edu.internet2.middleware.grouper.changeLog.esb2.consumer.EsbHttpPublisher.java

@Override
public boolean dispatchEvent(String eventJsonString, String consumerName) {
    // TODO Auto-generated method stub

    String urlString = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.url");
    String username = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.username", "");
    String password = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.password", "");
    if (LOG.isDebugEnabled()) {
        LOG.debug("Consumer name: " + consumerName + " sending " + GrouperUtil.indent(eventJsonString, false)
                + " to " + urlString);
    }/*from   w  ww  . ja v a  2  s  .c om*/
    int retries = GrouperLoaderConfig
            .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.retries", 0);
    int timeout = GrouperLoaderConfig
            .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.timeout", 60000);
    PostMethod post = new PostMethod(urlString);
    post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(retries, false));
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(timeout));
    post.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    RequestEntity requestEntity;
    try {
        requestEntity = new StringRequestEntity(eventJsonString, "application/json", "utf-8");

        post.setRequestEntity(requestEntity);
        HttpClient httpClient = new HttpClient();
        if (!(username.equals(""))) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Authenticating using basic auth");
            }
            URL url = new URL(urlString);
            httpClient.getState().setCredentials(new AuthScope(null, url.getPort(), null),
                    new UsernamePasswordCredentials(username, password));
            httpClient.getParams().setAuthenticationPreemptive(true);
            post.setDoAuthentication(true);
        }
        int statusCode = httpClient.executeMethod(post);
        if (statusCode == 200) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Status code 200 recieved, event sent OK");
            }
            return true;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Status code " + statusCode + " recieved, event send failed");
            }
            return false;
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:net.jadler.JadlerStubbingIntegrationTest.java

@Test
public void havingRawBody() throws IOException {
    onRequest().havingRawBodyEqualTo(BINARY_BODY).respond().withStatus(201);

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new ByteArrayRequestEntity(BINARY_BODY));

    final int status = client.executeMethod(method);
    assertThat(status, is(201));//w  w w.  j  av  a  2 s . c  o m
}

From source file:net.jadler.JadlerStubbingIntegrationTest.java

@Test
public void havingBody() throws Exception {
    onRequest().havingBodyEqualTo("postbody").havingBody(notNullValue()).havingBody(not(isEmptyOrNullString()))
            .respond().withStatus(201);//w  w w. j ava2 s .c o  m

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new StringRequestEntity("postbody", null, null));

    int status = client.executeMethod(method);
    assertThat(status, is(201));
}

From source file:net.jadler.JadlerStubbingIntegrationTest.java

@Test
public void havingEmptyBody() throws Exception {
    onRequest().havingBodyEqualTo("").havingBody(notNullValue()).havingBody(isEmptyString()).respond()
            .withStatus(201);/*from w  w w  . j  a v a  2s  . c om*/

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new StringRequestEntity("", null, null));

    int status = client.executeMethod(method);
    assertThat(status, is(201));
}

From source file:net.jadler.JadlerStubbingIntegrationTest.java

@Test
public void havingUTF8Body() throws Exception {

    onRequest().havingBodyEqualTo(STRING_WITH_DIACRITICS).respond().withStatus(201);

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(
            new StringRequestEntity(STRING_WITH_DIACRITICS, "text/plain", UTF_8_CHARSET.name()));

    int status = client.executeMethod(method);
    assertThat(status, is(201));//w  ww .j a  v  a2  s  .  com
}