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:com.example.android.test.app.DemoActivity.java

/**
 * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
 * messages to your app. Not needed for this demo since the device sends upstream messages
 * to a server that echoes back the message using the 'from' address in the message.
 *///from www  . j  a v  a 2s.  c  om
private void sendRegistrationIdToBackend() {

    /* General Post
        HttpURLConnection urlConnection = null;
        try {
    // Construct the URL for the OpenWeatherMap query
    String urlStr = "http://videosurv-906.appspot.com/register";
    Uri builtUri = Uri.parse(urlStr).buildUpon().build();
    URL url = new URL(builtUri.toString());
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("id", regid);
    urlConnection.connect();
    Log.i("RegistrationIdToBackend", "Registered");
            
        }catch (Exception e){
    Log.e("RegistrationIdToBackend", "Error ", e);
        }finally {
    if (urlConnection != null) {
        urlConnection.disconnect();
    }
        }
    */
    String urlStr = "http://videosurv-906.appspot.com/register";
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(urlStr);

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("id", regid));

    try {
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse response = client.execute(post);
        System.out.println("\nSending 'POST' request to URL : " + urlStr);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
    } catch (Exception e) {
        Log.e("RegistrationIdToBackend", "Error", e);
    }
}

From source file:com.cloudbees.eclipse.core.JenkinsService.java

synchronized private Object retrieveWithLogin(final DefaultHttpClient httpclient, final HttpRequestBase post,
        final List<NameValuePair> params, final boolean expectRedirect, final SubProgressMonitor monitor,
        final ResponseType responseType) throws UnsupportedEncodingException, IOException,
        ClientProtocolException, CloudBeesException, Exception {
    Object bodyResponse = null;/*from  w  ww.j av a  2  s.c om*/

    if (this.jenkins.username != null && this.jenkins.username.trim().length() > 0
            && this.jenkins.password != null && this.jenkins.password.trim().length() > 0) {
        post.addHeader("Authorization",
                "Basic " + Utils.toB64(this.jenkins.username + ":" + this.jenkins.password));
    }

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    if (params != null) {
        nvps.addAll(params);
    }

    if (post instanceof HttpEntityEnclosingRequest) {
        if (((HttpEntityEnclosingRequest) post).getEntity() == null) {
            ((HttpEntityEnclosingRequest) post).setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        }
    }

    //CloudBeesCorePlugin.getDefault().getLogger().info("Jenkins request: " + post.getURI());

    if (post instanceof HttpPost) {
        HttpPost pp = (HttpPost) post;

        String s;
        try {
            s = new Scanner(pp.getEntity().getContent()).useDelimiter("\\A").next();
        } catch (java.util.NoSuchElementException e) {
            s = "";
        }

        //CloudBeesCorePlugin.getDefault().getLogger().info("Jenkins request post params: " + s);

    }

    HttpResponse resp = httpclient.execute(post);
    switch (responseType) {
    case STRING:
        bodyResponse = Utils.getResponseBody(resp);
        break;
    case STREAM:
        bodyResponse = resp.getEntity().getContent();
        break;
    case HTTP:
        bodyResponse = resp;
        break;
    }

    Utils.checkResponseCode(resp, expectRedirect, jenkins.atCloud);

    return bodyResponse;
}

From source file:com.linecorp.armeria.server.AnnotatedHttpServiceTest.java

@Test
public void testDynamicHttpService_aggregation() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        HttpPost httpPost;

        httpPost = newHttpPost("/3/a/string");
        try (CloseableHttpResponse res = hc.execute(httpPost)) {
            assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
            assertThat(EntityUtils.toString(res.getEntity()), is(EntityUtils.toString(httpPost.getEntity())));
        }//  w w w.ja va  2 s  . co m
        httpPost = newHttpPost("/3/a/string-async1");
        try (CloseableHttpResponse res = hc.execute(httpPost)) {
            assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
            assertThat(EntityUtils.toString(res.getEntity()), is(EntityUtils.toString(httpPost.getEntity())));
        }
        httpPost = newHttpPost("/3/a/string-async2");
        try (CloseableHttpResponse res = hc.execute(httpPost)) {
            assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
            assertThat(EntityUtils.toString(res.getEntity()), is(EntityUtils.toString(httpPost.getEntity())));
        }
        httpPost = newHttpPost("/3/a/string-aggregate-response1");
        try (CloseableHttpResponse res = hc.execute(httpPost)) {
            assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
            assertThat(EntityUtils.toString(res.getEntity()), is(EntityUtils.toString(httpPost.getEntity())));
        }
        httpPost = newHttpPost("/3/a/string-aggregate-response2");
        try (CloseableHttpResponse res = hc.execute(httpPost)) {
            assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
            assertThat(EntityUtils.toString(res.getEntity()), is(EntityUtils.toString(httpPost.getEntity())));
        }
    }
}

From source file:D_common.E_xample.HttpClientExample.java

private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";

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

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

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    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());

    Header[] headers = response.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i].getName() + ": " + headers[i].getValue());
    }//w  w w .ja  va  2  s. co  m

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

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    System.out.println(result.toString());

}

From source file:org.codelibs.empros.agent.operation.rest.RestApiOperation.java

protected HttpPost getHttpPost(final List<Event> eventList) throws IOException {
    final HttpPost httpPost = new HttpPost(url);
    final Header[] headers = { new BasicHeader("Content-type", "application/json") };
    httpPost.setHeaders(headers);//from  w  ww . j  ava 2s . co  m

    final String json = generateJson(eventList);
    httpPost.setEntity(new StringEntity(json, "UTF-8"));

    if (logger.isDebugEnabled()) {
        logger.debug("requestLine: " + httpPost.getRequestLine());
        logger.debug("requestBody: " + EntityUtils.toString(httpPost.getEntity()));
    }
    return httpPost;
}

From source file:org.belio.service.gateway.Gateway.java

private synchronized boolean doPostXml(String xml) {

    try {//from   w  ww .  j  a  va 2 s .  c om
        // String urlParameters = "param1=a&param2=b&param3=c";

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.setHeader("HOST", "api.infobip.com");

        // add header
        // post.setHeader("User-Agent", USER_AGENT);
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("xml", xml));

        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);
        }

        System.out.println(result.toString());
    } catch (IOException ex) {
        Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
    }
    return true;
}

From source file:javafxapplication1.HttpClientExample.java

private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";

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

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

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    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  w w w .  jav a 2s.  c  om
    }

    System.out.println(result.toString());

}

From source file:org.apache.metamodel.neo4j.Neo4jRequestWrapperTest.java

@Test
public void testCreateCypherQueryWithAuthentication() {
    if (!isConfigured()) {
        System.err.println(getInvalidConfigurationMessage());
        return;/*from w  w w. j a  v  a2s  . co  m*/
    }

    CloseableHttpClient mockHttpClient = new CloseableHttpClient() {

        @Override
        public void close() throws IOException {
            // Do nothing
        }

        @Override
        public HttpParams getParams() {
            // Do nothing
            return null;
        }

        @Override
        public ClientConnectionManager getConnectionManager() {
            // Do nothing
            return null;
        }

        @Override
        protected CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, HttpContext context)
                throws IOException, ClientProtocolException {
            assertTrue(request instanceof HttpPost);
            HttpPost httpPost = (HttpPost) request;

            Header[] headers = httpPost.getHeaders("Authorization");
            assertNotNull(headers);
            assertEquals(1, headers.length);
            String base64Encoded = headers[0].getValue();
            base64Encoded = base64Encoded.replace("Basic ", "");
            String decoded = new String(BaseEncoding.base64().decode(base64Encoded), StandardCharsets.UTF_8);
            assertEquals("testUsername:testPassword", decoded);

            assertEquals("{\"statements\":[{\"statement\":\"MATCH (n) RETURN n;\"}]}",
                    EntityUtils.toString(httpPost.getEntity()));

            CloseableHttpResponse mockResponse = new MockClosableHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
            return mockResponse;
        }
    };

    Neo4jRequestWrapper wrapper = new Neo4jRequestWrapper(mockHttpClient,
            new HttpHost(getHostname(), getPort()), "testUsername", "testPassword", getServiceRoot());
    wrapper.executeCypherQuery("MATCH (n) RETURN n;");
    // Assertions are in the HttpClient
}

From source file:com.socialize.provider.BaseSocializeProvider.java

private HttpResponse executeRequest(HttpClient client, HttpUriRequest request) throws IOException {

    if (logger != null && logger.isDebugEnabled()) {

        StringBuilder builder = new StringBuilder();
        Header[] allHeaders = request.getAllHeaders();

        for (Header header : allHeaders) {
            builder.append(header.getName());
            builder.append(":");
            builder.append(header.getValue());
            builder.append("\n");
        }/*from w  w  w .  j  ava  2 s.  com*/

        if (logger.isDebugEnabled()) {
            logger.debug(
                    "REQUEST \nurl:[" + request.getURI().toString() + "] \nheaders:\n" + builder.toString());

        }

        if (request instanceof HttpPost) {
            HttpPost post = (HttpPost) request;
            HttpEntity entity = post.getEntity();
            String requestData = ioUtils.readSafe(entity.getContent());

            if (logger.isDebugEnabled()) {
                logger.debug("REQUEST \ndata:[" + requestData + "]");
            }
        }
    }

    return client.execute(request);
}

From source file:ADP.codeutils.HttpClientExample.java

public void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";

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

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

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    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 . c  o m*/
    }

    System.out.println(result.toString());

}