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.bpelunit.framework.control.deploy.activebpel.ActiveBPELDeployer.java

/**
 * @param re SOAP request entity to be sent to ActiveBPEL.
 * @return Response from the ActiveBPEL administration service.
 * @throws IOException/*from   www.jav  a2s . co  m*/
 */
private RequestResult sendRequestToActiveBPEL(final String url, RequestEntity re) throws IOException {
    PostMethod method = null;
    try {
        HttpClient client = new HttpClient(new NoPersistenceConnectionManager());
        if (fUsername != null && !"".equals(fUsername) && fPassword != null && !"".equals(fPassword)) {
            client.getState().setCredentials(new AuthScope(null, -1),
                    new UsernamePasswordCredentials(fUsername, fPassword));
        }
        method = new PostMethod(url);
        method.setRequestEntity(re);

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));
        method.addRequestHeader("SOAPAction", "");
        client.executeMethod(method);

        // We need to read the response body right now: if it is called
        // after the connection is released, it will only return null
        RequestResult result = new RequestResult();
        result.setStatusCode(method.getStatusCode());
        result.setResponseBody(method.getResponseBodyAsString());

        return result;
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.denimgroup.threadfix.cli.HttpRestUtils.java

public String httpPostFile(String request, File file, String[] paramNames, String[] paramVals) {

    Protocol.registerProtocol("https", new Protocol("https", new AcceptAllTrustFactory(), 443));

    PostMethod filePost = new PostMethod(request);

    filePost.setRequestHeader("Accept", "application/json");

    try {/*from   w  w w . j  a  v  a 2 s .  c  o m*/
        Part[] parts = new Part[paramNames.length + 1];
        parts[paramNames.length] = new FilePart("file", file);

        for (int i = 0; i < paramNames.length; i++) {
            parts[i] = new StringPart(paramNames[i], paramVals[i]);
        }

        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        filePost.setContentChunked(true);
        HttpClient client = new HttpClient();
        int status = client.executeMethod(filePost);
        if (status != 200) {
            System.err.println("Status was not 200.");
        }

        InputStream responseStream = filePost.getResponseBodyAsStream();

        if (responseStream != null) {
            return IOUtils.toString(responseStream);
        }

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "There was an error and the POST request was not finished.";
}

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public AuthenticationResponse authenticateSessionToken(String sessionToken) {
    PostMethod method = new PostMethod(baseUrl + AUTHENTICATE_TOKEN);
    AuthenticationTokenRequest request = new AuthenticationTokenRequest();
    request.setSessionToken(sessionToken);

    try {//from ww  w  .ja  v a  2s  .  com
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);

        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            AuthenticationResponse response = new AuthenticationResponse();
            response.setAuthenticated(false);
            return response;

        } else if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, AuthenticationResponse.class);

        } else {
            throw new RuntimeException("Failed to authenticate user, RESPONSE CODE: " + statusCode);
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.epam.wilma.gepard.testclient.MultiStubHttpPostRequestSender.java

private void createRequest(final MultiStubRequestParameters requestParameters, final PostMethod httpPost)
        throws IOException, ParserConfigurationException, SAXException {
    InputStream inputStream = requestParameters.getInputStream();
    if (requestParameters.getContentType().contains("fastinfoset")) {
        inputStream = fastInfosetCompressor.compress(inputStream);
    }//www.j  a  v a2  s.co m
    if (requestParameters.getContentEncoding().contains("gzip")) {
        inputStream = gzipCompressor.compress(inputStream);
        httpPost.setRequestHeader("Content-Encoding", requestParameters.getContentEncoding());
    }
    final InputStreamRequestEntity entity = new InputStreamRequestEntity(inputStream,
            requestParameters.getContentType());
    httpPost.setRequestEntity(entity);
    httpPost.setRequestHeader("Accept", requestParameters.getAcceptHeader());
    httpPost.addRequestHeader("Accept-Encoding", requestParameters.getAcceptEncoding());
    if (requestParameters.getSpecialHeader() != null) {
        httpPost.addRequestHeader("Special-Header", requestParameters.getSpecialHeader());
    }
    httpPost.addParameter("nextstatus", requestParameters.getStatus());
    httpPost.addParameter("direction", requestParameters.getDirection());
    httpPost.addParameter("groupname", requestParameters.getGroupName());
}

From source file:com.rallydev.integration.build.rest.RallyRestService.java

protected String doCreate(String xml, HttpClient httpClient, PostMethod post) throws IOException {
    try {/*from  www. j  a v a  2s  .c o  m*/
        // Prepare HTTP post
        // Request content will be retrieved directly
        // from the input stream
        RequestEntity entity = new StringRequestEntity(xml, "text/xml", "UTF-8");
        post.setRequestEntity(entity);

        logMessage("Issuing POST to " + post.getURI());

        // Execute request
        httpClient.getState().setCredentials(new AuthScope(host, port, null),
                new UsernamePasswordCredentials(username, password));
        setRequestHeaderInfo(post);

        setProxyParameters(httpClient);

        int result = httpClient.executeMethod(post);
        logMessage("POST response code was: " + result);

        // check status
        if (result != HttpStatus.SC_OK) {
            throw new IOException("HTTP POST Failed" + post.getStatusLine());
        }

        String response = inputStreamToString(post.getResponseBodyAsStream());

        if (!isValidResponse(response)) {
            throw new IOException("Create failed with errors: " + getErrors(response));
        }

        return response;
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}

From source file:net.duckling.ddl.service.resource.impl.ResourcePipeAgentServiceImpl.java

private JSONObject writeJson(JSONObject json) throws IOException {
    PostMethod method = new PostMethod(getQueryDomain() + "/pipe");
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    Header h = new Header();
    h.setName("content-type");
    h.setValue("application/json");
    method.addRequestHeader(h);//from w  w  w  .j a v  a2 s .  c  om
    StringRequestEntity body = new StringRequestEntity(json.toString());
    method.setRequestEntity(body);
    try {
        int status = getHttpClient().executeMethod(method);
        if (status >= 200 && status < 300) {
            String result = getResponseBody(method.getResponseBodyAsStream());
            return new JSONObject(result);
        } else {
            return null;
        }
    } catch (HttpException e) {
        new IOException(e);
    } catch (IOException e) {
        throw e;
    } catch (ParseException e) {
        new IOException(e);
    } finally {
        method.releaseConnection();
    }
    return null;
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public TransactionResult doTransaction(TransactionRequest transaction) {
    PostMethod method = new PostMethod(baseUrl + DO_TRANSACTION);

    log.info("Do Transaction, POST to: " + baseUrl + DO_TRANSACTION);
    try {//from w w  w .  j  av a 2s .co m
        String data = serialize(transaction);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, TransactionResult.class);

        }
        if (statusCode == HttpStatus.SC_FORBIDDEN) {
            throw new NegativeBalanceException(-1L);

        } else {
            throw new RuntimeException("Failed to do transaction, RESPONSE CODE: " + statusCode);
        }
    } catch (NegativeBalanceException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.epam.wilma.gepard.testclient.HttpPostRequestSender.java

private void createRequest(final RequestParameters requestParameters, final PostMethod httpPost)
        throws IOException, ParserConfigurationException, SAXException {
    InputStream inputStream = requestParameters.getInputStream();
    if (requestParameters.getContentType().contains("fastinfoset")) {
        inputStream = fastInfosetCompressor.compress(inputStream);
    }//from w  w w  .ja  v  a  2 s. c  o  m
    if (requestParameters.getContentEncoding().contains("gzip")) {
        inputStream = gzipCompressor.compress(inputStream);
        httpPost.setRequestHeader("Content-Encoding", requestParameters.getContentEncoding());
    }
    final InputStreamRequestEntity entity = new InputStreamRequestEntity(inputStream,
            requestParameters.getContentType());
    httpPost.setRequestEntity(entity);
    httpPost.setRequestHeader("Accept", requestParameters.getAcceptHeader());
    httpPost.addRequestHeader("Accept-Encoding", requestParameters.getAcceptEncoding());
    if (requestParameters.getSpecialHeader() != null) {
        httpPost.addRequestHeader("Special-Header", requestParameters.getSpecialHeader());
    }
    for (Entry<String, String> header : requestParameters.getCustomHeaders()) {
        httpPost.addRequestHeader(header.getKey(), header.getValue());
    }
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public void transfer(Long accountId, TransferRequest request) {
    String resource = String.format(baseUrl + ACCOUNT, accountId);
    PostMethod method = new PostMethod(resource);
    try {/*from w  w  w .ja  v  a 2  s  .  co  m*/
        String data = serialize(request);
        if (log.isTraceEnabled()) {
            log.trace("Transfer JSON data: " + data);
        }
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));
        // Execute the HTTP Call
        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:cuanto.api.CuantoConnector.java

/**
 * Creates a new TestRun on the Cuanto server using the values provided. A TestRun represents tests that were
 * executed together. The projectKey will be assigned the same projectKey as this CuantoConnector. The testRun
 * passed in will have it's id value assigned to the server-assigned ID of the created TestRun.
 *
 * @param testRun The test run to create.
 * @return The server-assigned ID of the created TestRun.
 *//*w  ww.  j  a  va 2s  .com*/
public Long addTestRun(TestRun testRun) {
    testRun.setProjectKey(getProjectKey());
    PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, getCuantoUrl() + "/api/addTestRun");
    try {
        post.setRequestEntity(new StringRequestEntity(testRun.toJSON(), "application/json", null));
        int httpStatus = getHttpClient().executeMethod(post);
        if (httpStatus == HttpStatus.SC_CREATED) {
            TestRun created = TestRun.fromJSON(getResponseBodyAsString(post));
            testRun.setProjectKey(this.projectKey);
            testRun.setId(created.getId());
            return created.getId();
        } else {
            throw new RuntimeException("Adding the TestRun failed with HTTP status code " + httpStatus + ": \n"
                    + getResponseBodyAsString(post));
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ParseException e) {
        throw new RuntimeException("Error parsing server response", e);
    }
}