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

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

Introduction

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

Prototype

public HttpEntity getEntity() 

Source Link

Usage

From source file:sadl.run.moe.MoeTest2.java

public static void main(String[] args) throws ClientProtocolException, IOException {
    final String postUrl = "http://pc-kbpool-8.cs.upb.de:6543/gp/next_points/epi";// put in your url
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { // Use this instead
        final HistoryData h = new HistoryData();
        final Configuration c = new Configuration();
        final PdttaParameters parameters = new PdttaParameters();
        for (final Parameter p : parameters.parameters) {
            c.config.put(p, p.getDefault());
        }/*from   ww w .  j a va  2s.co  m*/
        h.history.put(c, 0.5);
        final HttpPost post = new HttpPost(postUrl);
        final String s = parameters.toJsonString(20, h);
        // final String s = Files.readAllLines(Paths.get("testfile")).get(0);
        // final StringEntity postingString = new StringEntity(gson.toJson(p));// convert your pojo to json
        final StringEntity postingString = new StringEntity(s);// convert your pojo to json
        post.setEntity(postingString);
        System.out.println(EntityUtils.toString(post.getEntity(), "UTF-8"));
        post.setHeader("Content-type", "application/json");
        try (CloseableHttpResponse response = httpClient.execute(post)) {
            final String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(responseString);
        }
    }
    // This is the right query
    // {"domain_info": {"dim": 2, "domain_bounds": [{"max": 1.0, "min": 0.0},{"max": 0.0, "min": -1.0}]}, "gp_historical_info": {"points_sampled":
    // [{"value_var": 0.01, "value": 0.1, "point": [0.0,0.0]}, {"value_var": 0.01, "value": 0.2, "point": [1.0,-1.0]}]}, "num_to_sample": 1}
}

From source file:edu.ucla.cens.systemlog.Analytics.java

/**
 * Log information about network traffic uploads
 * /*from w  ww.j a  v a  2  s  .com*/
 * @param context
 * @param httpPost
 */
public static void network(Context context, HttpPost httpPost) {
    network(context, httpPost.getURI().getPath(), "upload", httpPost.getEntity().getContentLength());
}

From source file:org.jitsi.meet.test.util.JvbUtil.java

static private void triggerShutdown(HttpClient client, String jvbEndpoint, boolean force) throws IOException {
    String url = jvbEndpoint + "/colibri/shutdown";

    HttpPost post = new HttpPost(url);

    StringEntity requestEntity = new StringEntity(
            force ? "{ \"force-shutdown\": \"true\" }" : "{ \"graceful-shutdown\": \"true\" }",
            ContentType.APPLICATION_JSON);

    post.setEntity(requestEntity);//from   ww  w  . j a v  a2 s.  c o m

    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + post.getEntity());

    HttpResponse response = client.execute(post);

    int responseCode = response.getStatusLine().getStatusCode();
    if (200 != responseCode) {
        throw new RuntimeException(
                "Failed to trigger graceful shutdown on: " + jvbEndpoint + ", response code: " + responseCode);
    }
}

From source file:br.com.vpsa.oauth2android.common.Connection.java

/**
 *
 * Makes a standard http post request. The list of NameValuePairs can contain
 * all parameters and parameter designations for the request.
 *
 * @param parameterList//from ww w .jav a 2s .  c  o  m
 * @param url
 * @return <code>Response</code> with the servers response
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
public static Response httpPostRequest(List<NameValuePair> parameterList, String url)
        throws InvalidRequestException, InvalidClientException, InvalidGrantException,
        UnauthorizedClientException, UnsupportedGrantTypeException, InvalidScopeException, OAuthException,
        IOException {
    // prepare
    HttpClient httpclient = new DefaultHttpClient(); // client that executes the post request
    HttpPost httpPost = new HttpPost(url); // post request with the url
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(parameterList)); // set entity with all parameters
    } catch (UnsupportedEncodingException ex) {
        // won't bw thrown
    }

    // request
    Response response = new Response(httpclient.execute(httpPost));

    // set original request url to response (not important)
    response.setRequestUrl(EntityUtils.toString(httpPost.getEntity()));

    return response;
}

From source file:com.francelabs.datafari.utils.SendHttpRequest.java

public static String sendPost(String url, String agent, List<NameValuePair> urlParameters) throws Exception {

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    post.setHeader("User-Agent", agent);

    //      urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
    //         urlParameters.add(new BasicNameValuePair("cn", ""));
    //         urlParameters.add(new BasicNameValuePair("locale", ""));
    //         urlParameters.add(new BasicNameValuePair("caller", ""));
    //         urlParameters.add(new BasicNameValuePair("num", "12345"));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = client.execute(post);
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + post.getEntity());
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);//from   ww  w  .  j  a va2s  .  co  m
    }
    return result.toString();
}

From source file:com.nuance.expertassistant.HTTPConnection.java

public static String sendPost(String postURL, HashMap<String, String> paramMap) throws Exception {

    String url = postURL;//from   w w  w. ja v a 2s.  c o m

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    post.setHeader("User-Agent", USER_AGENT);

    if (paramMap != null) {
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        System.out.println(" Printing Parameters ");
        for (String key : paramMap.keySet()) {
            System.out.println(key + " :: " + paramMap.get(key));

            urlParameters.add(new BasicNameValuePair(key, paramMap.get(key)));

        }

        post.setEntity(new UrlEncodedFormEntity(urlParameters));
    }
    HttpResponse response = client.execute(post);
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + post.getEntity());
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuilder builder = new StringBuilder();
    for (String line = null; (line = rd.readLine()) != null;) {
        builder.append(line).append("\n");
    }
    /*
     System.out.print("JSON TEXT : " + builder.toString());
             
     String jsonText = builder.toString();
             
         jsonText = "{\"response\":" + jsonText + "}";
            
                     
             JSONObject object = new JSONObject(jsonText); */

    System.out.println(" The response code is :" + response.getStatusLine().getStatusCode());

    System.out.println(" The string returned is :" + builder.toString());

    return builder.toString();

}

From source file:tap.Tap.java

private static void testMethod() {
    try {//from   w w  w . j  a  va 2  s .c om

        String testdata = new Scanner(new File("testdata.txt")).useDelimiter("\\A").next();

        System.out.println("Uploading Ballots to the server!");

        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost("http://localhost:9000/3FF968A3B47CT34C");

        List<BasicNameValuePair> bnvp = new ArrayList();

        bnvp.add(new BasicNameValuePair("record", testdata));
        bnvp.add(new BasicNameValuePair("precinctID", Integer.toString((new Random()).nextInt())));

        /* Set entities for each of the url encoded forms of the NVP */
        post.setEntity(new UrlEncodedFormEntity(bnvp));

        System.out.println("Executing post..." + post.getEntity());

        /* Execute the post */
        client.execute(post);

        System.out.println("Upload complete!");

        /* Shutdown the connection when done */
        client.getConnectionManager().shutdown();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:eu.thecoder4.gpl.pleftdroid.PleftBroker.java

/**
 * //from  w  w w .  j  a  va2 s.  c  om
 */
static protected int setAvailability(String avails, int aid, String pserver, String user, String vcode) {
    int SC = HttpStatus.SC_INTERNAL_SERVER_ERROR;
    String aurl = pserver + "/a?id=" + aid + "&u=" + user + "&p=" + vcode;
    HttpClient client = getDefaultClient();

    SC = doAuthnForAppointment(client, aurl);

    HttpPost request = new HttpPost(pserver + REQ_SET_AVAILABILITY);

    List<NameValuePair> postParameters = new ArrayList<NameValuePair>(2);
    postParameters.add(new BasicNameValuePair("a", avails));
    postParameters.add(new BasicNameValuePair("id", Integer.toString(aid)));
    Log.i("PB", "a=" + avails + ",id=" + aid);
    try {
        request.setEntity(new UrlEncodedFormEntity(postParameters));
        Log.i("PB", request.getURI().toString());
        Log.i("PB", request.getEntity().toString());
        HttpResponse response = client.execute(request);
        SC = response.getStatusLine().getStatusCode();
        Log.i("PB sc", " " + SC);
        Log.i("PB", response.toString());

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return SC;
}

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());/*from   ww w . java 2 s. co  m*/
    log.append(Constants.LF);
    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:org.n52.oss.testdata.sml.GeneratorClient.java

/**
 * @param requestDoc//from  w w w  .  j a  v a  2 s  .  co  m
 * @return
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws HttpException
 */
private static XmlObject sendRequest(InsertSensorInfoRequestDocument requestDoc)
        throws UnsupportedEncodingException, IOException, HttpException {
    HttpPost request = new HttpPost(sirURL);
    request.setEntity(new StringEntity(requestDoc.xmlText(XmlTools.unconfiguredXmlOptionsForNamespaces()),
            STRING_REQUEST_ENCODING, STRING_REQUEST_CHARACTER_ENCODING));

    // String host = System.getProperty(SYSTEM_PROPERTY_PROXY_HOST);
    // String port = System.getProperty(SYSTEM_PROPERTY_PROXY_PORT);
    // if (host != null && host.length() > 0 && port != null && port.length() > 0) {
    // int portNumber = Integer.parseInt(port);
    // HostConfiguration hostConfig = new HostConfiguration();
    // hostConfig.setProxy(host, portNumber);
    // httpClient.setHostConfiguration(hostConfig);
    // }

    httpClient.execute(request);

    XmlObject response = null;
    try {
        response = XmlObject.Factory.parse(request.getEntity().getContent());
    } catch (XmlException e) {
        log.error("Error parsing response.", e);
        return null;
    }
    return response;
}