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.ibm.ra.remy.web.utils.BusinessRulesUtils.java

/**
 * Invoke Business Rules with JSON content
 *
 * @param content The payload of itineraries to send to Business Rules.
 * @return A JSON string representing the output of Business Rules.
 *//*from w  ww  .jav a2  s  .  c  om*/
public static String invokeRulesService(String json) throws Exception {
    PropertiesReader constants = PropertiesReader.getInstance();
    String username = constants.getStringProperty(USERNAME_KEY);
    String password = constants.getStringProperty(PASSWORD_KEY);
    String endpoint = constants.getStringProperty(EXECUTION_REST_URL_KEY)
            + constants.getStringProperty(RULE_APP_PATH_KEY);

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credentialsProvider).build();

    String responseString = "";

    try {
        HttpPost httpPost = new HttpPost(endpoint);
        httpPost.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
        StringEntity jsonEntity = new StringEntity(json, MessageUtils.ENCODING);
        httpPost.setEntity(jsonEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity, MessageUtils.ENCODING);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpClient.close();
    }
    return responseString;
}

From source file:in.huohua.peterson.network.NetworkUtils.java

public static HttpResponse httpQuery(final HttpRequest request) throws ClientProtocolException, IOException {
    final HttpRequestBase requestBase;
    if (request.getHttpMethod().equals(HttpRequest.HTTP_METHOD_GET)) {
        final StringBuilder builder = new StringBuilder(request.getUrl());
        if (request.getParams() != null) {
            if (!request.getUrl().contains("?")) {
                builder.append("?");
            } else {
                builder.append("&");
            }/*from ww  w.j av a  2s.c om*/
            builder.append(request.getParamsAsString());
        }
        final HttpGet get = new HttpGet(builder.toString());
        requestBase = get;
    } else if (request.getHttpMethod().equals(HttpRequest.HTTP_METHOD_POST)) {
        final HttpPost post = new HttpPost(request.getUrl());
        if (request.getEntity() != null) {
            post.setEntity(request.getEntity());
        } else {
            post.setEntity(new UrlEncodedFormEntity(request.getParamsAsList(), "UTF-8"));
        }
        requestBase = post;
    } else if (request.getHttpMethod().equals(HttpRequest.HTTP_METHOD_PUT)) {
        final HttpPut put = new HttpPut(request.getUrl());
        if (request.getEntity() != null) {
            put.setEntity(request.getEntity());
        } else {
            put.setEntity(new UrlEncodedFormEntity(request.getParamsAsList(), "UTF-8"));
        }
        requestBase = put;
    } else if (request.getHttpMethod().equals(HttpRequest.HTTP_METHOD_DELETE)) {
        final StringBuilder builder = new StringBuilder(request.getUrl());
        if (request.getParams() != null) {
            if (!request.getUrl().contains("?")) {
                builder.append("?");
            } else {
                builder.append("&");
            }
            builder.append(request.getParamsAsString());
        }
        final HttpDelete delete = new HttpDelete(builder.toString());
        requestBase = delete;
    } else {
        return null;
    }

    if (request.getHeaders() != null) {
        final Iterator<Map.Entry<String, String>> iterator = request.getHeaders().entrySet().iterator();
        while (iterator.hasNext()) {
            final Map.Entry<String, String> kv = iterator.next();
            requestBase.setHeader(kv.getKey(), kv.getValue());
        }
    }
    return HTTP_CLIENT.execute(requestBase);
}

From source file:com.niyo.network.NetworkUtilities.java

/**
 * Connects to the Voiper server, authenticates the provided username and
 * password.//w w  w.ja  va 2  s.com
 * 
 * @param username The user's username
 * @param password The user's password
 * @param handler The hander instance from the calling UI thread.
 * @param context The context of the calling Activity.
 * @return boolean The boolean result indicating whether the user was
 *         successfully authenticated.
 */
public static boolean authenticate(String username, String password, Handler handler, final Context context) {
    final HttpResponse resp;

    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, username));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
    HttpEntity entity = null;
    try {
        entity = new UrlEncodedFormEntity(params);
    } catch (final UnsupportedEncodingException e) {
        // this should never happen.
        throw new AssertionError(e);
    }
    final HttpPost post = new HttpPost(AUTH_URI);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    maybeCreateHttpClient();

    sendResult(true, handler, context);
    return true;

    //        try {
    //            resp = mHttpClient.execute(post);
    //            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    //                if (Log.isLoggable(TAG, Log.VERBOSE)) {
    //                    Log.v(TAG, "Successful authentication");
    //                }
    //                sendResult(true, handler, context);
    //                return true;
    //            } else {
    //                if (Log.isLoggable(TAG, Log.VERBOSE)) {
    //                    Log.v(TAG, "Error authenticating" + resp.getStatusLine());
    //                }
    //                sendResult(false, handler, context);
    //                return false;
    //            }
    //        } catch (final IOException e) {
    //            if (Log.isLoggable(TAG, Log.VERBOSE)) {
    //                Log.v(TAG, "IOException when getting authtoken", e);
    //            }
    //            sendResult(false, handler, context);
    //            return false;
    //        } finally {
    //            if (Log.isLoggable(TAG, Log.VERBOSE)) {
    //                Log.v(TAG, "getAuthtoken completing");
    //            }
    //        }
}

From source file:com.arpnetworking.kairosdb.KairosHelper.java

/**
 * Creates the JSON body for a datapoint query.
 *
 * @param startTimestamp starting timestamp
 * @param endTimestamp ending timestamp/*from w  w  w.  j a v a2  s.  c  o  m*/
 * @param metric metric to query for
 * @param aggregator aggregator to apply
 * @param aggregatorParameters extra parameters to apply to the aggregator
 * @return JSON Object to POST to KairosDB
 * @throws JSONException on JSON error
 */
public static HttpPost queryFor(final long startTimestamp, final long endTimestamp, final String metric,
        final String aggregator, final JSONObject aggregatorParameters) throws JSONException {
    final JSONObject sampling = new JSONObject();
    sampling.put("value", 10);
    sampling.put("unit", "minutes");
    final JSONObject aggregatorJson = new JSONObject();
    aggregatorJson.put("name", aggregator);
    aggregatorJson.put("sampling", sampling);

    if (aggregatorParameters != null) {
        final JSONArray names = aggregatorParameters.names();
        if (names != null) {
            for (int i = 0; i < names.length(); i++) {
                aggregatorJson.putOnce((String) names.get(i), aggregatorParameters.get((String) names.get(i)));
            }
        }
    }

    final JSONArray aggregators = new JSONArray();
    aggregators.put(aggregatorJson);
    final JSONObject query = queryJsonFor(startTimestamp, endTimestamp, metric);
    query.getJSONArray("metrics").getJSONObject(0).put("aggregators", aggregators);

    final HttpPost lookup = new HttpPost(KairosHelper.getEndpoint() + "/api/v1/datapoints/query");
    try {
        lookup.setEntity(new StringEntity(query.toString()));
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return lookup;
}

From source file:es.ugr.swad.swadroid.webservices.RestEasy.java

public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost request = new HttpPost(url);
    StringEntity s = new StringEntity(c.toString());
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");

    request.setEntity(s);
    request.addHeader("accept", "application/json");

    return httpclient.execute(request);
}

From source file:org.opencastproject.remotetest.server.resource.IngestResources.java

public static HttpResponse addZippedMediaPackage(TrustedHttpClient client, InputStream mediaPackage)
        throws Exception {
    HttpPost post = new HttpPost(getServiceUrl() + "addZippedMediaPackage");
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("mediaPackage", new InputStreamBody(mediaPackage, "mediapackage.zip"));
    post.setEntity(entity);
    return client.execute(post);
}

From source file:com.beginner.core.utils.HttpUtil.java

/**
 * <p>To request the POST way.</p>
 * /*w  ww .ja va2 s .  com*/
 * @param url      request URI
 * @param json      request parameter(json format string)
 * @param timeout   request timeout time in milliseconds(The default timeout time for 30 seconds.)
 * @return String   response result
 * @throws Exception
 * @since 1.0.0
 */
public static String post(String url, String json, Integer timeout) throws Exception {

    // Validates input
    if (StringUtils.isBlank(url))
        throw new IllegalArgumentException("The url cannot be null and cannot be empty.");

    //The default timeout time for 30 seconds
    if (null == timeout)
        timeout = 30000;

    String result = null;
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;

    try {
        httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "text/plain");
        httpPost.setEntity(new StringEntity(json, "UTF-8"));

        httpResponse = httpClient.execute(httpPost);

        HttpEntity entity = httpResponse.getEntity();

        result = EntityUtils.toString(entity);

        EntityUtils.consume(entity);
    } catch (Exception e) {
        logger.error("POST?", e);
        return null;
    } finally {
        if (null != httpResponse)
            httpResponse.close();
        if (null != httpClient)
            httpClient.close();
    }
    return result;
}

From source file:org.eclipse.cbi.common.signing.Signer.java

public static void signFile(File source, File target, String signerUrl)
        throws IOException, MojoExecutionException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(signerUrl);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    builder.addPart("file", new FileBody(source));
    post.setEntity(builder.build());

    HttpResponse response = client.execute(post);
    int statusCode = response.getStatusLine().getStatusCode();

    HttpEntity resEntity = response.getEntity();

    if (statusCode >= 200 && statusCode <= 299 && resEntity != null) {
        InputStream is = resEntity.getContent();
        try {/* www  .j  a v  a2 s. com*/
            FileUtils.copyStreamToFile(new RawInputStreamFacade(is), target);
        } finally {
            IOUtil.close(is);
        }
    } else if (statusCode >= 500 && statusCode <= 599) {
        InputStream is = resEntity.getContent();
        String message = IOUtil.toString(is, "UTF-8");
        throw new NoHttpResponseException("Server failed with " + message);
    } else {
        throw new MojoExecutionException("Signer replied " + response.getStatusLine());
    }
}

From source file:ca.dal.cs.csci4126.quizboard.library.HttpClient.java

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

    try {//from  ww  w  . java 2  s  . c  o  m
        DefaultHttpClient httpclient = new DefaultHttpClient();
        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();
        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
            JSONObject jsonObjRecv = new JSONObject(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;
        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}

From source file:com.jt.https.test.send.java

public static String PostTo(String content) {
    String responseMessage = null;
    String filePath = "";
    if (!filePath.endsWith("/")) {
        filePath = filePath + "/";
    }/*  ww w .j a  v a 2  s  .c o  m*/
    HttpClient httpclient = new DefaultHttpClient();
    try {
        KeyStore keystore = KeyStore.getInstance("jks");
        KeyStore trustStore = KeyStore.getInstance("jks");

        FileInputStream keystoreInstream = new FileInputStream(
                new File("F:\\temp\\?\\lz\\\\bis-stg-sdb.jks"));
        FileInputStream trustStoreInstream = new FileInputStream(
                new File("F:\\temp\\?\\lz\\\\EXV_GROUP_BIS_IFRONT_JTLZX_100.jks"));
        //FileInputStream keystoreInstream = new FileInputStream(new File("F:\\temp\\?\\lz\\\\pingan2jiangtai_test.jks"));
        //FileInputStream trustStoreInstream = new FileInputStream(new File("F:\\temp\\?\\lz\\\\pingan2jiangtai_test_trust.jks"));
        try {
            keystore.load(keystoreInstream, "123456".toCharArray());
            trustStore.load(trustStoreInstream, "paic1234".toCharArray());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } finally {
            keystoreInstream.close();
            trustStoreInstream.close();
        }
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.SSL, keystore, "123456",
                trustStore, null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                        return true;
                    }
                }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", 8107, socketFactory);

        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        HttpPost post = new HttpPost("https://222.68.184.181:8107");

        StringEntity entity = new StringEntity(content, "text/html", "UTF-8");
        post.setEntity(entity);
        HttpResponse res = httpclient.execute(post);
        HttpEntity resEntity = res.getEntity();
        if (resEntity != null) {
            responseMessage = convertStreamToString(resEntity.getContent());
            System.out.println("???" + content);
            System.out.println("?" + responseMessage);
        }

    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return responseMessage;
}