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

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

Introduction

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

Prototype

public HttpPost(final String uri) 

Source Link

Usage

From source file:org.apache.camel.component.restlet.RestletMultiMethodsEndpointTest.java

@Test
public void testPostMethod() throws Exception {
    HttpResponse response = doExecute(new HttpPost("http://localhost:" + portNum + "/users/homer"));

    assertHttpResponse(response, 200, "text/plain", "POST");
}

From source file:com.avinashbehera.sabera.network.HttpClient.java

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

    try {/*  w ww.java2s .c om*/
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 60 * 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 60 * 1000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
        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();
        Log.d(TAG, "httpPostReuest = " + httpPostRequest.toString());
        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
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;
        }

    } catch (Exception e) {
        Log.d(TAG, "catch block");
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    Log.d(TAG, "SendHttpPostUsingHttpClient returning null");
    return null;
}

From source file:com.github.segator.scaleway.api.Utils.java

public static HttpRequestBase buildRequest(String type, String requestPath, String accessToken) {
    HttpRequestBase request = null;/*from w  ww  .j ava  2  s  .c  o m*/
    switch (type) {
    case "POST":
        request = new HttpPost(requestPath);
        break;
    case "GET":
        request = new HttpGet(requestPath);
        break;
    case "DELETE":
        request = new HttpDelete(requestPath);
        break;
    case "PATCH":
        request = new HttpPatch(requestPath);
        break;
    }
    request.setHeader(ScalewayConstants.HEADER_AUTH_TOKEN, accessToken);
    request.setHeader(HttpHeaders.CONTENT_TYPE, ScalewayConstants.JSON_APPLICATION);
    return request;
}

From source file:com.subgraph.vega.impl.scanner.requests.PostParameterRequestBuilder.java

private HttpUriRequest createPostRequest(List<NameValuePair> parameters) {
    final URI u = createUri(getBasePath());
    final HttpPost req = new HttpPost(u);
    req.setEntity(createParameterEntity(parameters));
    return req;//from  w ww  . j a v  a2 s  .c o  m
}

From source file:httpServerClient.app.QuickStart.java

public static void sendMessage(String[] args) throws Exception {
    // arguments to run Quick start POST:
    // args[0] POST
    // args[1] IPAddress of server
    // args[2] port No.
    // args[3] user name
    // args[4] myMessage
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {/*from ww w.  j  a va 2s.  co m*/
        HttpPost httpPost = new HttpPost("http://" + args[1] + ":" + args[2] + "/sendMessage");
        // httpPost.setEntity(new StringEntity("lubo je kral"));
        httpPost.setEntity(
                new StringEntity("{\"name\":\"" + args[3] + "\",\"myMessage\":\"" + args[4] + "\"}"));
        CloseableHttpResponse response1 = httpclient.execute(httpPost);
        // The underlying HTTP connection is still held by the response
        // object
        // to allow the response content to be streamed directly from the
        // network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally
        // clause.
        // Please note that if response content is not fully consumed the
        // underlying
        // connection cannot be safely re-used and will be shut down and
        // discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();

            /*
             * Vypisanie odpovede do konzoly a discard dat zo serveru.
             */

            System.out.println(EntityUtils.toString(entity1));
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

    } finally {
        httpclient.close();
    }
}

From source file:nl.coralic.beta.sms.utils.http.HttpHandler.java

private static Response doPost(String url, List<NameValuePair> postdata) {
    HttpClient httpclient = getHttpClient();
    try {/*from w  w w.ja  va 2 s  . co  m*/
        HttpPost httpost = new HttpPost(url);
        httpost.setEntity(new UrlEncodedFormEntity(postdata, HTTP.UTF_8));
        HttpResponse response = httpclient.execute(httpost);
        if (response.getStatusLine().getStatusCode() == 200) {
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            return new Response(responseHandler.handleResponse(response));
        } else {
            return new Response(R.string.ERR_PROV_NO_RESP);
        }
    } catch (Exception e) {
        return new Response(R.string.ERR_CONN_ERR);
    } finally {
        // Release the resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.semantictools.web.upload.FileUploadClient.java

public void post(String contentType, File file) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(serviceURI);

    FileEntity entity = new FileEntity(file, contentType);
    post.setEntity(entity);/*ww  w . jav  a  2 s .  com*/

    HttpResponse response = client.execute(post);

    int status = response.getStatusLine().getStatusCode();
    switch (status) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
        System.out.println();
        break;

    default:
        System.out.println(" ERROR: " + status);

    }

}

From source file:att.jaxrs.client.Tag.java

public static String addTag(Tag tag) {
    final long tag_id = getExistingRecord(tag.getTag_name());
    if (-1L != tag_id) {
        return "{response:{Tag: 'EXISTING_RECORD'},tag_id:" + tag_id + "}";
    }//  ww  w. j  a v a 2s . c o  m
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("tag_name", tag.getTag_name()));

    HttpResponse result;
    String resultStr = "";

    try {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.INSERT_TAG_RESOURCE);
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
        result = httpClient.execute(post);
        System.out.println(Constants.RESPONSE_STATUS_CODE + result);
        resultStr = Util.getStringFromInputStream(result.getEntity().getContent());
        System.out.println(Constants.RESPONSE_BODY + resultStr);

    } catch (Exception e) {
        System.out.println(e.getMessage());

    }
    return resultStr;
}

From source file:org.talend.dataprep.api.service.command.dataset.UpdateColumn.java

private UpdateColumn(final String dataSetId, final String columnId, final InputStream body) {
    super(GenericCommand.DATASET_GROUP);
    execute(() -> {/* www .j a v a 2 s.  c o m*/
        final HttpPost post = new HttpPost(
                datasetServiceUrl + "/datasets/" + dataSetId + "/column/" + columnId); //$NON-NLS-1$ //$NON-NLS-2$
        post.setHeader("Content-Type", APPLICATION_JSON_VALUE);
        post.setEntity(new InputStreamEntity(body));
        return post;
    });
    onError(e -> new TDPException(APIErrorCodes.UNABLE_TO_CREATE_OR_UPDATE_DATASET, e,
            ExceptionContext.build().put("id", dataSetId)));
    on(HttpStatus.OK).then(asNull());
}

From source file:org.dasein.cloud.aws.platform.CloudFrontAction.java

public HttpRequestBase getMethod(String url) {
    switch (this) {
    case DELETE_DISTRIBUTION:
        return new HttpDelete(url);
    case LIST_DISTRIBUTIONS:
    case GET_DISTRIBUTION:
        return new HttpGet(url);
    case CREATE_DISTRIBUTION:
        return new HttpPost(url);
    case UPDATE_DISTRIBUTION:
        return new HttpPut(url);
    }//  w w w.  j a va  2  s .  c om
    return null;
}