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

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

Introduction

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

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:com.volley.android.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from w w  w .  j  a  va2 s. com
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Request.Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Request.Method.GET:
        return new HttpGet(request.getUrl());
    case Request.Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Request.Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Request.Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.wudoumi.batter.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///  w  w  w  . j a  v  a2 s .c  om
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case RequestType.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case RequestType.GET:
        return new HttpGet(request.getUrl());
    case RequestType.DELETE:
        return new HttpDelete(request.getUrl());
    case RequestType.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case RequestType.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.mr.http.toolbox.MR_HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*from w  ww .j a v  a2  s.  co  m*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(MR_Request<?> request,
        Map<String, String> additionalHeaders) throws MR_AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.autonavi.gxdtaojin.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*from   w  w w  .j  a v  a  2s . co  m*/
@SuppressWarnings("deprecation")
/* protected */static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:org.aludratest.cloud.selenium.impl.SeleniumResourceImpl.java

private static void performPost(String url, String data) {
    CloseableHttpClient client = HttpClientBuilder.create().build();

    try {/* w  w  w.ja v  a2 s . c o  m*/
        HttpPost request = new HttpPost(url);
        request.setEntity(new StringEntity(data, ContentType.DEFAULT_BINARY));
        client.execute(request);
    } catch (IOException e) {
        // ignore silently
        LOG.debug("Could not execute a POST on url " + url, e);
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:utils.ImportExportUtils.java

/**
 * retrieve a access token with requested scope
 *
 * @param scope required token scope//from w w  w  .  j a va  2s  .  co m
 * @param  consumerCredentials encoded consumerKey and consumerSecret
 */

static String getAccessToken(String scope, String consumerCredentials) {

    ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance();
    String url = config.getGatewayUrl();
    String responseString;

    //mapping payload to a List
    List<NameValuePair> params = new ArrayList<>(4);
    params.add(new BasicNameValuePair(ImportExportConstants.TOKEN_GRANT_TYPE,
            ImportExportConstants.DEFAULT_GRANT_TYPE));
    params.add(new BasicNameValuePair(ImportExportConstants.USERNAME, config.getUsername()));
    params.add(new BasicNameValuePair(ImportExportConstants.DEFAULT_GRANT_TYPE,
            String.valueOf(config.getPassword())));
    params.add(new BasicNameValuePair(ImportExportConstants.SCOPE_CONSTANT, scope));

    //REST API call for get tokens
    CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
    try {
        HttpPost request = new HttpPost(url);
        request.setEntity(new UrlEncodedFormEntity(params, ImportExportConstants.CHARSET));
        request.setHeader(HttpHeaders.AUTHORIZATION,
                ImportExportConstants.AUTHORIZATION_KEY_SEGMENT + " " + consumerCredentials);
        CloseableHttpResponse response;
        response = client.execute(request);
        responseString = EntityUtils.toString(response.getEntity());
        JSONObject jsonObj = (JSONObject) new JSONParser().parse(responseString);
        return ((String) jsonObj.get(ImportExportConstants.ACCESS_TOKEN));
    } catch (ParseException e) {
        log.error("error occurred while getting the access token");
    } catch (UnsupportedEncodingException | ClientProtocolException e) {
        String errormsg = "error occurred while passing the payload for token generation";
        log.error(errormsg, e);
        return null;
    } catch (IOException e) {
        String errormsg = "error occurred while generating tokens";
        log.error(errormsg, e);
        return null;
    } finally {
        IOUtils.closeQuietly(client);
    }
    return null;
}

From source file:com.mongolduu.android.ng.misc.HttpConnector.java

public static String httpPOST(String url, List<NameValuePair> nameValuePairs)
        throws ClientProtocolException, IOException {
    HttpClient httpClient = createHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpClient.execute(httpPost);
    if (response.getStatusLine().getStatusCode() >= 400) {
        throw new IOException("HTTP client error: " + response.getStatusLine().getStatusCode());
    }//from  w w  w. j a  va2  s . co  m
    return processEntity(response.getEntity());
}

From source file:com.bacic5i5j.framework.toolbox.web.WebUtils.java

/**
 * ??//from   ww  w . j  a va2 s. co  m
 *
 * @param params
 * @param url
 * @return
 */
public static String post(Map<String, String> params, String url) {
    String result = "";

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    List<NameValuePair> nvps = generateURLParams(params);
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage() + " : " + e.getCause());
    }

    CloseableHttpResponse response = null;

    try {
        response = httpClient.execute(httpPost);
    } catch (IOException e) {
        log.error(e.getMessage() + " : " + e.getCause());
    }

    if (response != null) {
        StatusLine statusLine = response.getStatusLine();
        log.info("??: " + statusLine.getStatusCode());
        if (statusLine.getStatusCode() == 200 || statusLine.getStatusCode() == 302) {
            try {
                InputStream is = response.getEntity().getContent();
                int count = is.available();
                byte[] buffer = new byte[count];
                is.read(buffer);
                result = new String(buffer);
            } catch (IOException e) {
                log.error("???: " + e.getMessage());
            }
        }
    }

    return result;
}

From source file:org.surveydroid.android.coms.WebClient.java

private static synchronized boolean postJsonToUrl(Context ctxt, String url, String value, boolean firstCall) {
    HttpClient httpclient = getClient(ctxt);
    HttpPost httpPost = new HttpPost(url);

    try {/*from w w  w.j  a  v  a2 s  .  c o m*/
        StringEntity se = new StringEntity(value);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpPost.setEntity(se);

        // Execute HTTP Post Request
        HttpResponse response;
        try {
            response = httpclient.execute(httpPost);
        } catch (SSLException e) {
            //make sure this isn't the recursive call
            if (!firstCall)
                throw new ApiException("Untrusted certificate");
            //switch to using the other client
            swapKeyStore(ctxt);
            //the just do a recursive call
            return postJsonToUrl(ctxt, url, value, false);
        }

        Util.d(null, TAG, "Content: " + getInputStreamAsString(ctxt, response.getEntity().getContent()));

        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HTTP_STATUS_OK)
            return true;
    } catch (Exception e) {
        Util.e(null, TAG, Util.fmt(e));
    }
    return false;
}

From source file:org.aludratest.cloud.selenium.impl.SeleniumResourceImpl.java

private static void closeSelenium1Session(String url, String sessionId) {
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("cmd", "testComplete"));
    urlParameters.add(new BasicNameValuePair("sessionId", sessionId));

    CloseableHttpClient client = HttpClientBuilder.create().build();

    try {//from ww  w . j  a  v  a  2s.  co m
        HttpPost request = new HttpPost(url);
        request.setEntity(new UrlEncodedFormEntity(urlParameters));
        client.execute(request);
    } catch (IOException e) {
        // ignore silently
        LOG.debug("Could not execute a POST on url " + url, e);
    } finally {
        IOUtils.closeQuietly(client);
    }
}