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.arthackday.killerapp.util.Util.java

public static String makeJsonRpcCall(String jsonRpcUrl, JSONObject payload, String authToken) {
    Log.d(LOG_TAG, jsonRpcUrl + " " + payload.toString());
    try {//from  w w w .  ja v a  2 s  . c om
        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(jsonRpcUrl);

        if (authToken != null) {
            httpPost.addHeader(new BasicHeader("Authorization", "GoogleLogin auth=" + authToken));
        }

        httpPost.setEntity(new StringEntity(payload.toString(), "UTF-8"));

        HttpResponse httpResponse = client.execute(httpPost);
        if (200 == httpResponse.getStatusLine().getStatusCode()) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024);

            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }

            return sb.toString();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.fpmislata.clientejson.ClienteClienteTest.java

private static Cliente addCliente(String url, Cliente cliente) throws IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("accept", "application/json; charset=UTF-8");
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    String jsonString = gson.toJson(cliente);
    StringEntity input = new StringEntity(jsonString, "UTF-8");
    input.setContentType("application/json");
    httpPost.setEntity(input);
    HttpResponse response = httpClient.execute(httpPost);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }//from   w  ww  . j  a  v a2s .c o  m

    String personaResult = readObject(response);
    return gson.fromJson(personaResult, Cliente.class);
}

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

public static HttpResponse start(TrustedHttpClient client, String mediapackage, String workflowDefinition,
        String properties) throws Exception {
    HttpPost post = new HttpPost(getServiceUrl() + "start");
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("mediapackage", mediapackage));
    params.add(new BasicNameValuePair("definition", workflowDefinition));
    params.add(new BasicNameValuePair("properties", properties));
    post.setEntity(new UrlEncodedFormEntity(params));
    return client.execute(post);
}

From source file:com.networknt.client.oauth.TokenHelper.java

public static TokenResponse getToken(TokenRequest tokenRequest) throws ClientException {
    String url = tokenRequest.getServerUrl() + tokenRequest.getUri();
    TokenResponse tokenResponse = null;//from w w  w.  j  av a 2s .  c o m

    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader(Constants.AUTHORIZATION,
            getBasicAuthHeader(tokenRequest.getClientId(), tokenRequest.getClientSecret()));

    try {
        CloseableHttpClient client = Client.getInstance().getSyncClient();
        httpPost.setEntity(getEntity(tokenRequest));
        HttpResponse response = client.execute(httpPost);
        tokenResponse = handleResponse(response);

    } catch (JsonProcessingException jpe) {
        logger.error("JsonProcessingException: ", jpe);
        throw new ClientException("JsonProcessingException: ", jpe);
    } catch (UnsupportedEncodingException uee) {
        logger.error("UnsupportedEncodingException", uee);
        throw new ClientException("UnsupportedEncodingException: ", uee);
    } catch (IOException ioe) {
        logger.error("IOException: ", ioe);
        throw new ClientException("IOException: ", ioe);
    }
    return tokenResponse;
}

From source file:eu.cassandra.training.utils.APIUtilities.java

/**
 * This function is used to send the entity models to the Cassandra Server,
 * specifically on the connected user's Library.
 * /* ww  w  .j  a  v a  2  s.  com*/
 * @param message
 *          The JSON schema of the entity.
 * @param suffix
 *          The library the model must be sent to.
 * @return the id of the entity model provided by the server.
 * @throws IOException
 * @throws AuthenticationException
 * @throws NoSuchAlgorithmException
 */
public static String sendEntity(String message, String suffix)
        throws IOException, AuthenticationException, NoSuchAlgorithmException {

    System.out.println(message);
    HttpPost httppost = new HttpPost(url + suffix);

    StringEntity entity = new StringEntity(message, "UTF-8");
    entity.setContentType("application/json");
    httppost.setEntity(entity);
    System.out.println("executing request: " + httppost.getRequestLine());

    HttpResponse response = httpclient.execute(httppost, localcontext);
    HttpEntity responseEntity = response.getEntity();
    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
    System.out.println(responseString);

    DBObject dbo = (DBObject) JSON.parse(responseString);

    DBObject dataObj = (DBObject) dbo.get("data");

    return dataObj.get("_id").toString();

}

From source file:com.flurry.proguard.UploadMapping.java

/**
 * Register this upload with the metadata service
 *
 * @param projectId the id of the project
 * @param payload the JSON body to send/*  ww  w .jav  a  2s. c om*/
 * @param token the Flurry auth token
 * @return the id of the created upload
 */
private static String createUpload(String projectId, String payload, String token) throws IOException {
    String postUrl = String.format("%s/project/%s/uploads", METADATA_BASE, projectId);
    List<Header> requestHeaders = getMetadataHeaders(token);
    HttpPost postRequest = new HttpPost(postUrl);
    postRequest.setEntity(new StringEntity(payload, Charset.forName("UTF-8")));
    try (CloseableHttpResponse response = executeHttpRequest(postRequest, requestHeaders)) {
        expectStatus(response, HttpURLConnection.HTTP_CREATED);
        JSONObject jsonObject = getJsonFromEntity(response.getEntity());
        return jsonObject.getJSONObject("data").get("id").toString();
    } finally {
        postRequest.releaseConnection();
    }
}

From source file:com.alphabetbloc.accessmrs.utilities.NetworkUtils.java

public static void postEntity(HttpClient client, String url, MultipartEntity entity) throws IOException {
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(entity);
    HttpResponse response = client.execute(httppost);
    // verify response is okay
    int responseCode = response.getStatusLine().getStatusCode();
    if (App.DEBUG)
        Log.v(TAG, "httppost response=" + responseCode);
    if (responseCode != HttpURLConnection.HTTP_OK)
        throw new IOException(App.getApp().getString(R.string.error_connection));
}

From source file:utils.UtilsFunction.java

public static String testPostJsonToServer() throws UnsupportedEncodingException, IOException {
    HttpPost postRequest = new HttpPost("http://localhost:8080/post/json");
    postRequest.setHeader("Content-type", "application/json");
    String jsonData = new Gson().toJson(new Pojo());
    StringEntity postData = new StringEntity(jsonData);
    postRequest.setEntity(postData);
    HttpResponse res = client.execute(postRequest);
    String dataResponse = getStringFromResponse(res);
    return dataResponse;
}

From source file:org.apache.solr.handler.TestBlobHandler.java

public static void postData(CloudSolrClient cloudClient, String baseUrl, String blobName, ByteBuffer bytarr)
        throws IOException {
    HttpPost httpPost = null;
    HttpEntity entity;/*  ww w .  j  a  v  a2 s  .c  o  m*/
    String response = null;
    try {
        httpPost = new HttpPost(baseUrl + "/.system/blob/" + blobName);
        httpPost.setHeader("Content-Type", "application/octet-stream");
        httpPost.setEntity(new ByteArrayEntity(bytarr.array(), bytarr.arrayOffset(), bytarr.limit()));
        entity = cloudClient.getLbClient().getHttpClient().execute(httpPost).getEntity();
        try {
            response = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            Map m = (Map) ObjectBuilder.getVal(new JSONParser(new StringReader(response)));
            assertFalse("Error in posting blob " + getAsString(m), m.containsKey("error"));
        } catch (JSONParser.ParseException e) {
            log.error("$ERROR$", response, e);
            fail();
        }
    } finally {
        httpPost.releaseConnection();
    }
}

From source file:weave.utils.BugReportUtils.java

private static void submitReport(Throwable e, String comment) {
    TraceUtils.trace(TraceUtils.STDOUT, "-> Sending Bug report.............");

    try {//from   w w w  .  j  a  v a 2  s.com
        String stack = TraceUtils.getStackTrace(e);
        Map<String, String> map = new HashMap<String, String>();
        map.put("os", Settings.getExactOS());
        map.put("updr_ver", Settings.UPDATER_VER);
        map.put("instll_ver", Settings.INSTALLER_VER);
        map.put("comment", comment);
        map.put("stack", stack);

        JSONObject json = new JSONObject(map);
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(Settings.API_BUG_REPORT);
        System.out.println(json.toString());

        StringEntity params = new StringEntity("json=" + json.toString());
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");
        post.setEntity(params);

        HttpResponse response = client.execute(post);
        InputStream is = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = "";
        while ((line = br.readLine()) != null)
            sb.append(line + Settings.N_L);

        System.out.println("");
        System.out.println(sb.toString());
        System.out.println("");

    } catch (ClientProtocolException e1) {
        TraceUtils.trace(TraceUtils.STDERR, e1);
    } catch (IOException e1) {
        TraceUtils.trace(TraceUtils.STDERR, e1);
    }

    TraceUtils.put(TraceUtils.STDOUT, "DONE");
}