Example usage for org.apache.http.client.methods HttpPost toString

List of usage examples for org.apache.http.client.methods HttpPost toString

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPost toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.ljt.openapi.demo.util.HttpUtil.java

private static void logPost(HttpPost post) {
    StringBuilder log = new StringBuilder();
    log.append("send request:");
    log.append(post.toString());
    log.append(Constants.LF);/*from  w  ww.  j  a  va  2  s. com*/
    Header[] headers = post.getAllHeaders();
    log.append("headers:");
    log.append(Constants.LF);
    for (int i = 0; i < headers.length; i++) {

        log.append(headers[i].getName() + ":" + headers[i].getValue());
        log.append(Constants.LF);
    }

    HttpEntity entity = post.getEntity();
    if (entity == null) {

        log.append("body is emputy");
        logger.info(log.toString());
        return;
    }

    log.append("body:");

    log.append(Constants.LF);
    try {
        List<String> entitys = org.apache.commons.io.IOUtils.readLines(entity.getContent(), Constants.ENCODING);
        for (Iterator<String> it = entitys.iterator(); it.hasNext();) {
            log.append(it.next());
        }
    } catch (UnsupportedOperationException | IOException e) {
        logger.warn(e.getMessage(), e);
    }
    logger.info(log.toString());
}

From source file:password.pwm.ws.client.rest.RestClientHelper.java

public static String makeOutboundRestWSCall(final PwmApplication pwmApplication, final Locale locale,
        final String url, final String jsonRequestBody)
        throws PwmOperationalException, PwmUnrecoverableException {
    final HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("Accept", PwmConstants.AcceptValue.json.getHeaderValue());
    if (locale != null) {
        httpPost.setHeader("Accept-Locale", locale.toString());
    }// ww  w  .  j  a v  a2s .c  o m
    httpPost.setHeader("Content-Type", PwmConstants.ContentTypeValue.json.getHeaderValue());
    final HttpResponse httpResponse;
    try {
        final StringEntity stringEntity = new StringEntity(jsonRequestBody);
        stringEntity.setContentType(PwmConstants.AcceptValue.json.getHeaderValue());
        httpPost.setEntity(stringEntity);
        LOGGER.debug("beginning external rest call to: " + httpPost.toString() + ", body: " + jsonRequestBody);
        httpResponse = PwmHttpClient.getHttpClient(pwmApplication.getConfig()).execute(httpPost);
        final String responseBody = EntityUtils.toString(httpResponse.getEntity());
        LOGGER.trace("external rest call returned: " + httpResponse.getStatusLine().toString() + ", body: "
                + responseBody);
        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            final String errorMsg = "received non-200 response code ("
                    + httpResponse.getStatusLine().getStatusCode() + ") when executing web-service";
            LOGGER.error(errorMsg);
            throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg));
        }
        return responseBody;
    } catch (IOException e) {
        final String errorMsg = "http response error while executing external rest call, error: "
                + e.getMessage();
        LOGGER.error(errorMsg);
        throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg), e);
    }
}

From source file:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingHttpClient(String URL, JSONObject jsonObjSend) {

    try {// w w w . ja v  a 2s.c o m
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 60 * 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 60 * 1000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        //httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        //httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        Log.d(TAG, "httpPostReuest = " + httpPostRequest.toString());
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;
        }

    } catch (Exception e) {
        Log.d(TAG, "catch block");
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    Log.d(TAG, "SendHttpPostUsingHttpClient returning null");
    return null;
}

From source file:org.megam.api.http.TransportMachinery.java

public static TransportResponse post(TransportTools nuts) throws ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(nuts.urlString());
    System.out.println("NUTS" + nuts.toString());
    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {
            httppost.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }/*from w  w w  .j a v  a2s  .c  om*/
    }
    if (nuts.fileEntity() != null) {
        httppost.setEntity(nuts.fileEntity());
    }
    if (nuts.pairs() != null && (nuts.contentType() == null)) {
        httppost.setEntity(new UrlEncodedFormEntity(nuts.pairs()));
    }

    if (nuts.contentType() != null) {
        httppost.setEntity(new StringEntity(nuts.contentString(), nuts.contentType()));
    }
    TransportResponse transportResp = null;
    System.out.println(httppost.toString());
    try {
        HttpResponse httpResp = httpclient.execute(httppost);
        transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(),
                httpResp.getLocale());
    } finally {
        httppost.releaseConnection();
    }
    return transportResp;

}

From source file:info.guardianproject.net.http.HttpManager.java

public static String doPost(String serviceEndpoint, Properties props) throws Exception {

    DefaultHttpClient httpClient = new SocksHttpClient();

    HttpPost request = new HttpPost(serviceEndpoint);
    HttpResponse response = null;/*from   w w  w  .ja v a2s.  com*/
    HttpEntity entity = null;

    StringBuffer sbResponse = new StringBuffer();

    Enumeration<Object> enumProps = props.keys();
    String key, value = null;

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    while (enumProps.hasMoreElements()) {
        key = (String) enumProps.nextElement();
        value = (String) props.get(key);
        nvps.add(new BasicNameValuePair(key, value));

        Log.i(TAG, "adding nvp:" + key + "=" + value);
    }

    UrlEncodedFormEntity uf = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);

    Log.i(TAG, uf.toString());

    request.setEntity(uf);

    request.setHeader("Content-Type", POST_MIME_TYPE);

    Log.i(TAG, "http post request: " + request.toString());

    // Post, check and show the result (not really spectacular, but works):
    response = httpClient.execute(request);
    entity = response.getEntity();

    int status = response.getStatusLine().getStatusCode();

    // we assume that the response body contains the error message
    if (status != HttpStatus.SC_OK) {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        entity.writeTo(ostream);

        Log.e(TAG, " error status code=" + status);
        Log.e(TAG, ostream.toString());

        return null;
    } else {
        InputStream content = response.getEntity().getContent();
        // <consume response>

        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;

        while ((line = reader.readLine()) != null)
            sbResponse.append(line);

        content.close(); // this will also close the connection

        return sbResponse.toString();
    }

}

From source file:com.openideals.android.net.HttpManager.java

public static String doPost(String serviceEndpoint, Properties props) throws Exception {

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost request = new HttpPost(serviceEndpoint);
    HttpResponse response = null;// w  w  w.  j  ava2  s.co  m
    HttpEntity entity = null;

    StringBuffer sbResponse = new StringBuffer();

    Enumeration<Object> enumProps = props.keys();
    String key, value = null;

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    while (enumProps.hasMoreElements()) {
        key = (String) enumProps.nextElement();
        value = (String) props.get(key);
        nvps.add(new BasicNameValuePair(key, value));

        Log.i(TAG, "adding nvp:" + key + "=" + value);
    }

    UrlEncodedFormEntity uf = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);

    Log.i(TAG, uf.toString());

    request.setEntity(uf);

    request.setHeader("Content-Type", POST_MIME_TYPE);

    Log.i(TAG, "http post request: " + request.toString());

    // Post, check and show the result (not really spectacular, but works):
    response = httpClient.execute(request);
    entity = response.getEntity();

    int status = response.getStatusLine().getStatusCode();

    // we assume that the response body contains the error message
    if (status != HttpStatus.SC_OK) {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        entity.writeTo(ostream);

        Log.e(TAG, " error status code=" + status);
        Log.e(TAG, ostream.toString());

        return null;
    } else {
        InputStream content = response.getEntity().getContent();
        // <consume response>

        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;

        while ((line = reader.readLine()) != null)
            sbResponse.append(line);

        content.close(); // this will also close the connection

        return sbResponse.toString();
    }

}

From source file:org.openbaton.integration.test.utils.Utils.java

public static String getAccessToken(String nfvoIp, String nfvoPort, String username, String password)
        throws IOException, SDKException {
    HttpClient httpClient = HttpClientBuilder.create().build();

    HttpPost httpPost = new HttpPost("http://" + nfvoIp + ":" + nfvoPort + "/oauth/token");

    httpPost.setHeader("Authorization",
            "Basic " + Base64.encodeBase64String("openbatonOSClient:secret".getBytes()));
    List<BasicNameValuePair> parametersBody = new ArrayList<>();
    parametersBody.add(new BasicNameValuePair("grant_type", "password"));
    parametersBody.add(new BasicNameValuePair("username", username));
    parametersBody.add(new BasicNameValuePair("password", password));

    log.debug("Username is: " + username);
    log.debug("Password is: " + password);

    httpPost.setEntity(new UrlEncodedFormEntity(parametersBody, StandardCharsets.UTF_8));

    org.apache.http.HttpResponse response = null;
    log.debug("httpPost is: " + httpPost.toString());
    response = httpClient.execute(httpPost);

    String responseString = null;
    responseString = EntityUtils.toString(response.getEntity());
    int statusCode = response.getStatusLine().getStatusCode();
    log.trace(statusCode + ": " + responseString);

    if (statusCode != 200) {
        ParseComError error = new Gson().fromJson(responseString, ParseComError.class);
        log.error("Status Code [" + statusCode + "]: Error signing-in [" + error.error + "] - "
                + error.error_description);
        throw new SDKException("Status Code [" + statusCode + "]: Error signing-in [" + error.error + "] - "
                + error.error_description);
    }// ww  w  . jav a  2 s .c o  m
    JsonObject jobj = new Gson().fromJson(responseString, JsonObject.class);
    log.trace("JsonTokeAccess is: " + jobj.toString());
    String bearerToken = null;
    try {
        String token = jobj.get("value").getAsString();
        log.trace(token);
        bearerToken = "Bearer " + token;
    } catch (NullPointerException e) {
        String error = jobj.get("error").getAsString();
        if (error.equals("invalid_grant")) {
            throw new SDKException(
                    "Error during authentication: " + jobj.get("error_description").getAsString(), e);
        }
    }
    return bearerToken;
}

From source file:com.sonatype.nexus.perftest.ossrh.ProjectProvisioningOperation.java

@Override
public void perform(ClientRequestInfo requestInfo) throws Exception {
    DefaultHttpClient httpclient = getHttpClient();

    StringBuilder url = new StringBuilder(nexusBaseurl);
    if (!nexusBaseurl.endsWith("/")) {
        url.append("/");
    }/*from   w  ww .  ja va  2  s.  co  m*/
    url.append("service/siesta/onboard");

    url.append("?users=").append("jvanzyl");
    url.append("&groupId=").append(String.format("test.nexustaging-%03d", requestInfo.getRequestId()));

    HttpPost request = new HttpPost(url.toString());

    HttpResponse response = httpclient.execute(request);

    String json = EntityUtils.toString(response.getEntity());

    if (!isSuccess(response)) {
        throw new IOException(request.toString() + " : " + response.getStatusLine().toString());
    }
}

From source file:org.apache.geode.rest.internal.web.controllers.RestAPITestBase.java

CloseableHttpResponse executeFunctionThroughRestCall(String function, String regionName, String filter,
        String jsonBody, String groups, String members) {
    System.out.println("Entering executeFunctionThroughRestCall");
    CloseableHttpResponse value = null;/*from  w  w  w.  jav  a  2s .  c  om*/
    try {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        Random randomGenerator = new Random();
        int restURLIndex = randomGenerator.nextInt(restURLs.size());

        HttpPost post = createHTTPPost(function, regionName, filter, restURLIndex, groups, members, jsonBody);

        System.out.println("Request: POST " + post.toString());
        value = httpclient.execute(post);
    } catch (Exception e) {
        fail("unexpected exception", e);
    }
    return value;
}

From source file:nl.nn.adapterframework.http.HttpResponseMock.java

public InputStream doPost(HttpHost host, HttpPost request, HttpContext context) throws IOException {
    assertEquals("POST", request.getMethod());
    StringBuilder response = new StringBuilder();
    String lineSeparator = System.getProperty("line.separator");
    response.append(request.toString() + lineSeparator);

    Header[] headers = request.getAllHeaders();
    for (Header header : headers) {
        response.append(header.getName() + ": " + header.getValue() + lineSeparator);
    }// w w w .j  ava 2s.  c o  m
    HttpEntity entity = request.getEntity();
    if (entity instanceof MultipartEntity) {
        MultipartEntity multipartEntity = (MultipartEntity) entity;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        multipartEntity.writeTo(baos);
        String contentType = multipartEntity.getContentType().getValue();
        String boundary = getBoundary(contentType);
        contentType = contentType.replaceAll(boundary, "IGNORE");
        response.append("Content-Type: " + contentType + lineSeparator);

        response.append(lineSeparator);
        String content = new String(baos.toByteArray());
        content = content.replaceAll(boundary, "IGNORE");
        response.append(content);
    } else {
        response.append(lineSeparator);
        response.append(EntityUtils.toString(entity));
    }

    return new ByteArrayInputStream(response.toString().getBytes());
}