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.arpnetworking.kairosdb.KairosHelper.java

/**
 * Creates the JSON body for a datapoint query.
 *
 * @param startTimestamp starting timestamp
 * @param endTimestamp ending timestamp/* w w  w . j  av  a 2 s  .c o m*/
 * @param metric metric to query for
 * @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)
        throws JSONException {
    final JSONObject query = queryJsonFor(startTimestamp, endTimestamp, metric);

    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:com.jts.main.helper.Http.java

public static String sendPost(String url, URLParameter param) {
    String retval = "";
    HttpClient httpClient = new DefaultHttpClient();
    try {// w ww . j  a v  a2  s . c o  m
        HttpPost request = new HttpPost(My.base_url + url);
        StringEntity params = new StringEntity(param.get());
        request.addHeader("content-type", "application/x-www-form-urlencoded");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        // handle response here...
        retval = org.apache.http.util.EntityUtils.toString(response.getEntity());
        org.apache.http.util.EntityUtils.consume(response.getEntity());
    } catch (IOException | ParseException ex) {
        errMsg = ex.getMessage();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return retval;
}

From source file:com.oakley.fon.util.HttpUtils.java

public static HttpResult getUrlByPost(String url, Map<String, String> params, Map<String, String> headers,
        int maxRetries) throws IOException {
    String result = null;/* w w w .ja  v  a 2  s.  c om*/
    int retries = 0;
    HttpContext localContext = new BasicHttpContext();
    DefaultHttpClient httpclient = getHttpClient();

    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    if (params != null) {
        Set<Entry<String, String>> paramsSet = params.entrySet();
        for (Entry<String, String> entry : paramsSet) {
            formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }

    UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formParams, UTF8);
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(postEntity);

    if (headers != null) {
        Set<Entry<String, String>> headersSet = headers.entrySet();
        for (Entry<String, String> entry : headersSet) {
            httppost.setHeader(entry.getKey(), entry.getValue());
        }
    }

    while (retries < maxRetries && result == null) {
        try {
            retries++;
            HttpEntity responseEntity = httpclient.execute(httppost, localContext).getEntity();
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity).trim();
            }
        } catch (SocketException se) {
            if (retries > maxRetries) {
                throw se;
            } else {
                Log.v(TAG, "SocketException, retrying " + retries, se);
            }
        }
    }

    HttpHost attribute = (HttpHost) localContext.getAttribute("http.target_host");
    String targetHost = null;
    if (attribute != null) {
        targetHost = attribute.toURI();
    }

    return new HttpResult(result, (BasicHttpResponse) localContext.getAttribute("http.response"), targetHost);
}

From source file:gov.nist.appvet.tool.synchtest.util.ReportUtil.java

/** This method should be used for sending files back to AppVet. */
public static boolean sendInNewHttpRequest(String appId, String reportFilePath, ToolStatus reportStatus) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
    HttpConnectionParams.setSoTimeout(httpParameters, 1200000);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    httpClient = SSLWrapper.wrapClient(httpClient);
    try {/* w w  w  .  j  a  v  a2 s.  c o m*/
        /*
         * To send reports back to AppVet, the following parameters must be
         * sent: - command: SUBMIT_REPORT - username: AppVet username -
         * password: AppVet password - appid: The app ID - toolid: The ID of
         * this tool - toolrisk: The risk assessment (LOW, MODERATE, HIGH,
         * ERROR) - report: The report file.
         */
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("command", new StringBody("SUBMIT_REPORT", Charset.forName("UTF-8")));
        entity.addPart("username", new StringBody(Properties.appvetUsername, Charset.forName("UTF-8")));
        entity.addPart("password", new StringBody(Properties.appvetPassword, Charset.forName("UTF-8")));
        entity.addPart("appid", new StringBody(appId, Charset.forName("UTF-8")));
        entity.addPart("toolid", new StringBody(Properties.toolId, Charset.forName("UTF-8")));
        entity.addPart("toolrisk", new StringBody(reportStatus.name(), Charset.forName("UTF-8")));
        File report = new File(reportFilePath);
        FileBody fileBody = new FileBody(report);
        entity.addPart("file", fileBody);
        HttpPost httpPost = new HttpPost(Properties.appvetUrl);
        httpPost.setEntity(entity);
        // Send the report to AppVet
        log.debug("Sending report file to AppVet");
        final HttpResponse response = httpClient.execute(httpPost);
        log.debug("Received from AppVet: " + response.getStatusLine());
        // Clean up
        httpPost = null;
        return true;
    } catch (Exception e) {
        log.error(e.toString());
        return false;
    }
}

From source file:org.graylog2.systeminformation.Sender.java

public static void send(Map<String, Object> info, Core server) {
    HttpClient httpClient = new DefaultHttpClient();

    try {/*from  w  ww . j  ava  2s .com*/
        HttpPost request = new HttpPost(getTarget(server));

        List<NameValuePair> nameValuePairs = Lists.newArrayList();
        nameValuePairs.add(new BasicNameValuePair("systeminfo", JSONValue.toJSONString(info)));
        request.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpClient.execute(request);

        if (response.getStatusLine().getStatusCode() != 201) {
            LOG.warn("Response code for system statistics was not 201, but "
                    + response.getStatusLine().getStatusCode());
        }
    } catch (Exception e) {
        LOG.warn("Could not send system statistics.", e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:utils.TestUtils.java

public static String httpPost(String url, String data) throws Exception {
    CloseableHttpResponse resp = null;//from   w ww .j a va2 s  .co m
    try {
        HttpPost post = new HttpPost(url);
        post.setEntity(new ByteArrayEntity(data.getBytes("UTF-8")));
        resp = HTTP.execute(post);
        return EntityUtils.toString(resp.getEntity(), "UTF-8");
    } finally {
        closeQuietly(resp);
    }
}

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

/**
 * Creates the JSON body for a datapoint POST.
 *
 * @param timestamp timestamp of the datapoint
 * @param number the number/*from  www.  ja  v  a 2 s  .c  o m*/
 * @param metricName the name of the metric
 * @return JSON Array to POST to KairosDB
 * @throws JSONException on a JSON error
 */
public static HttpPost postNumber(final int timestamp, final Double number, final String metricName)
        throws JSONException {
    final JSONArray json = new JSONArray();
    final JSONObject metric = new JSONObject();
    final JSONArray datapoints = new JSONArray();
    final JSONArray datapoint = new JSONArray();
    final JSONObject tags = new JSONObject();
    tags.put("host", "foo_host");

    datapoint.put(timestamp);
    datapoint.put(number);
    datapoints.put(datapoint);

    metric.put("name", metricName).put("ttl", 600).put("datapoints", datapoints).put("tags", tags);

    json.put(metric);
    final HttpPost post = new HttpPost(KairosHelper.getEndpoint() + "/api/v1/datapoints");
    try {
        post.setEntity(new StringEntity(json.toString()));
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    post.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    return post;
}

From source file:eu.eexcess.partnerrecommender.test.PartnerRecommenderTestHelper.java

@SuppressWarnings({ "resource", "deprecation" })
static public ResultList getRecommendations(String deploymentContext, int port, StringEntity params) {

    HttpClient httpClient = new DefaultHttpClient();
    ResultList resultList = null;/*from w  ww . ja va2s. co  m*/
    try {

        HttpPost request = new HttpPost(
                "http://localhost:" + port + "/" + deploymentContext + "/partner/recommend/");
        request.addHeader("content-type", "application/xml");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        String responseString = EntityUtils.toString(response.getEntity());

        resultList = PartnerRecommenderTestHelper.parseResponse(responseString);

    } catch (Exception ex) {
        System.out.println(ex);
    } finally {

        httpClient.getConnectionManager().shutdown();
    }

    return resultList;
}

From source file:net.wedjaa.elasticparser.tester.ESSearchTester.java

private static void populateTest() {
    // Get the bulk index as a stream
    InputStream bulkStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("bulk-insert.json");
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();

    HttpResponse response;//from   ww  w  . j av  a 2 s  .  c om
    // Drop the index if it's there
    HttpDelete httpdelete = new HttpDelete("http://localhost:9500/unit");
    try {
        response = httpclient.execute(httpdelete);
        System.out.println("Index Deleted: " + response);
        httpclient.close();
    } catch (ClientProtocolException protoException) {
        System.err.println("Protocol Error while deleting index: " + protoException);
    } catch (IOException ioException) {
        System.err.println("IO Error while deleting index: " + ioException);
    }

    HttpPost httppost = new HttpPost("http://localhost:9500/_bulk");

    InputStreamEntity isEntity = new InputStreamEntity(bulkStream);
    httppost.setEntity(isEntity);

    try {
        httpclient = HttpClientBuilder.create().build();
        response = httpclient.execute(httppost);
        System.out.println(response.getStatusLine());
        httpclient.close();
    } catch (ClientProtocolException protoException) {
        System.err.println("Protocol Error while bulk indexing: " + protoException);
    } catch (IOException ioException) {
        System.err.println("IO Error while bulk indexing: " + ioException);
    }
    System.out.println("Waiting for index to settle down...");
    while (countIndexed() < 50) {
        System.out.println("...");
    }
    System.out.println("...done!");
}

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

/**
 * Creates the JSON body for a datapoint POST.
 *
 * @param timestamp timestamp of the datapoint
 * @param histogram the histogram/*from   w  w w.  j  a v  a  2s  .c  o m*/
 * @param metricName the name of the metric
 * @return JSON Array to POST to KairosDB
 * @throws JSONException on a JSON error
 */
public static HttpPost postHistogram(final int timestamp, final Histogram histogram, final String metricName)
        throws JSONException {
    final JSONArray json = new JSONArray();
    final JSONObject metric = new JSONObject();
    final JSONArray datapoints = new JSONArray();
    final JSONArray datapoint = new JSONArray();
    final JSONObject tags = new JSONObject();
    tags.put("host", "foo_host");

    datapoint.put(timestamp);
    datapoint.put(histogram.getJson());
    datapoints.put(datapoint);

    metric.put("name", metricName).put("ttl", 600).put("type", "histogram").put("datapoints", datapoints)
            .put("tags", tags);

    json.put(metric);
    final HttpPost post = new HttpPost(KairosHelper.getEndpoint() + "/api/v1/datapoints");
    try {
        post.setEntity(new StringEntity(json.toString()));
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    post.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    return post;
}