Example usage for org.apache.http.entity StringEntity setContentEncoding

List of usage examples for org.apache.http.entity StringEntity setContentEncoding

Introduction

In this page you can find the example usage for org.apache.http.entity StringEntity setContentEncoding.

Prototype

public void setContentEncoding(Header header) 

Source Link

Usage

From source file:com.careerly.utils.HttpClientUtils.java

/**
 * url??Jsonpost?// ww  w  .j  a  v  a2s  .  c o  m
 *
 * @param url
 * @param jsonData
 * @return
 */
public static String post(String url, String jsonData, String defaultEncoding) {
    defaultEncoding = HttpClientUtils.getDefaultEncoding(defaultEncoding);
    String content = null;
    try {
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(jsonData, defaultEncoding);
        entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(entity);
        HttpResponse response = HttpClientUtils.client.execute(post);
        content = EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        HttpClientUtils.logger.error(String.format("post [%s] happens error ", url), e);
    }
    return content;
}

From source file:com.optimusinfo.elasticpath.cortex.common.Utils.java

public static int putRequest(String deleteUrl, JSONObject requestBody, String accessToken, String contentType,
        String contentTypeString, String authorizationString, String accessTokenInitializer) {
    // Making HTTP request
    try {//w w w .  ja  va 2  s . c  o m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        Log.i("PUT REQUEST", deleteUrl);
        HttpPut httpPut = new HttpPut(deleteUrl);
        httpPut.setHeader(contentTypeString, contentType);
        httpPut.setHeader(authorizationString, accessTokenInitializer + " " + accessToken);

        if (requestBody != null) {
            StringEntity requestEntity = new StringEntity(requestBody.toString());
            requestEntity.setContentEncoding("UTF-8");
            requestEntity.setContentType(contentType);
            httpPut.setEntity(requestEntity);
        }

        HttpResponse httpResponse = httpClient.execute(httpPut);
        return httpResponse.getStatusLine().getStatusCode();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return 0;
}

From source file:com.optimusinfo.elasticpath.cortex.common.Utils.java

/**
 * //from w w w.  j  a  v a 2 s .  com
 * @param accessToken
 * @param postURL
 * @param ent
 * @param contentType
 * @return
 */
public static int postData(String postUrl, JSONObject requestBody, String accessToken, String contentType,
        String accessTokenInitializer) {
    HttpClient client = new DefaultHttpClient();
    try {

        HttpPost postRequest = new HttpPost(postUrl);
        postRequest.setHeader(Constants.RequestHeaders.CONTENT_TYPE_STRING, contentType);
        postRequest.setHeader(Constants.RequestHeaders.AUTHORIZATION_STRING,
                accessTokenInitializer + " " + accessToken);

        if (requestBody != null) {
            StringEntity requestEntity = new StringEntity(requestBody.toString());
            requestEntity.setContentEncoding("UTF-8");
            requestEntity.setContentType(contentType);
            postRequest.setEntity(requestEntity);
        }

        HttpResponse responsePOST = client.execute(postRequest);
        Log.i("POST RESPONSE", EntityUtils.toString(responsePOST.getEntity()));

        return responsePOST.getStatusLine().getStatusCode();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    } finally {
        client.getConnectionManager().shutdown();
    }
    return 0;
}

From source file:es.ucm.look.data.remote.restful.RestMethod.java

/**
 * Used to insert an element/*  www  .j a  va  2  s . c  o  m*/
 * 
 * @param url
 *       Element URI
 * @param c
 *       The element represented with a JSON
 * @return
 *       The response
 */
public static HttpResponse doPost(String url, JSONObject c) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost request = new HttpPost(url);
    StringEntity s = null;
    try {
        s = new StringEntity(c.toString());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");

    request.setEntity(s);
    request.addHeader("accept", "application/json");

    try {
        return httpclient.execute(request);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:es.ucm.look.data.remote.restful.RestMethod.java

/**
 * To Update an element/*from  ww w . java 2 s. c o  m*/
 * 
 * @param url
 *       Element URI
 * @param c
 *       The element to update represented with a JSON
 * @return
 *       The response
 */
public static HttpResponse doPut(String url, JSONObject c) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPut request = new HttpPut(url);
    StringEntity s = null;
    try {
        s = new StringEntity(c.toString());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");

    request.setEntity(s);
    request.addHeader("accept", "application/json");

    try {
        return httpclient.execute(request);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;

}

From source file:azureml_besapp.AzureML_BESApp.java

/**
 * Call REST API to submit job to Azure ML for batch predictions
 * @return response from the REST API// www  .j av  a 2 s .c  om
 */
public static String besHttpPost() {

    HttpPost post;
    HttpClient client;
    StringEntity entity;

    try {
        // create HttpPost and HttpClient object
        post = new HttpPost(apiurl);
        client = HttpClientBuilder.create().build();

        // setup output message by copying JSON body into 
        // apache StringEntity object along with content type
        entity = new StringEntity(jsonBody, HTTP.UTF_8);
        entity.setContentEncoding(HTTP.UTF_8);
        entity.setContentType("text/json");

        // add HTTP headers
        post.setHeader("Accept", "text/json");
        post.setHeader("Accept-Charset", "UTF-8");

        // set Authorization header based on the API key
        post.setHeader("Authorization", ("Bearer " + apikey));
        post.setEntity(entity);

        // Call REST API and retrieve response content
        HttpResponse authResponse = client.execute(post);

        jobId = EntityUtils.toString(authResponse.getEntity()).replaceAll("\"", "");

        return jobId;

    } catch (Exception e) {

        return e.toString();
    }

}

From source file:csic.ceab.movelab.beepath.Util.java

public static boolean patch2DjangoJSONArray(Context context, JSONArray jsonArray, String uploadurl,
        String username, String password) {

    String response = "";

    try {/*from   www  .j ava 2 s  .co m*/

        JSONObject obj = new JSONObject();
        obj.put("objects", jsonArray);
        JSONArray emptyarray = new JSONArray();
        obj.put("deleted_objects", emptyarray);

        CredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        // Create a new HttpClient and Post Header
        HttpPatch httppatch = new HttpPatch(uploadurl);

        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 60000);
        HttpConnectionParams.setTcpNoDelay(myParams, true);

        httppatch.setHeader("Content-type", "application/json");

        DefaultHttpClient httpclient = new DefaultHttpClient();

        httpclient.setCredentialsProvider(credProvider);
        // ByteArrayEntity bae = new ByteArrayEntity(obj.toString()
        // .getBytes("UTF8"));

        StringEntity se = new StringEntity(obj.toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        // bae.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
        // "application/json"));
        httppatch.setEntity(se);

        // Execute HTTP Post Request

        HttpResponse httpResponse = httpclient.execute(httppatch);

        response = httpResponse.getStatusLine().toString();

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

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

    if (response.contains("ACCEPTED")) {
        return true;
    } else {
        return false;
    }

}

From source file:com.lostad.app.base.util.RequestUtil.java

public static String postRequest(final String url, final StringEntity params, String token,
        final boolean isSingleton) throws Exception {
    String json = null;/* www  . ja  va 2  s .c o  m*/
    HttpClient client = HttpClientManager.getHttpClient(isSingleton);
    HttpEntity resEntity = null;
    HttpPost post = new HttpPost(url);
    if (Validator.isNotEmpty(token)) {
        post.addHeader("token", token);
    }

    try {
        //long t1 = System.currentTimeMillis();

        if (params != null) {
            params.setContentEncoding(HTTP.UTF_8);
            params.setContentType("application/x-www-form-urlencoded");
            post.setEntity(params);
        }

        HttpResponse response = client.execute(post, new BasicHttpContext());
        resEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200
            //?
            json = EntityUtils.toString(resEntity);
        }
    } catch (Exception e) {
        if (post != null) {
            post.abort();
        }
        throw e;
    } finally {

        if (resEntity != null) {
            try {
                resEntity.consumeContent();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        client.getConnectionManager().closeExpiredConnections();
    }
    return json;
}

From source file:com.strato.hidrive.api.connection.httpgateway.request.JSONPostRequest.java

protected HttpRequestBase createHttpRequest(String requestUri, HttpRequestParamsVisitor<?> visitor)
        throws UnsupportedEncodingException {
    HttpPost httpPost = new HttpPost(requestUri);
    String jsonString = "";
    if (jsonObject != null) {
        jsonString = jsonObject.toString();
    } else if (jsonArray != null) {
        jsonString = jsonArray.toString();
    }//from   w w  w.  jav  a2s . c  om

    StringEntity stringEntity = new StringEntity(jsonString, "UTF-8");
    stringEntity.setContentEncoding("UTF-8");
    stringEntity.setContentType(CONTENT_TYPE_APPLICATION_JSON);
    httpPost.setEntity(stringEntity);

    return httpPost;
}

From source file:com.rastating.droidbeard.net.ErrorReportTask.java

public JSONObject postData(String url, JSONObject obj) {
    HttpClient client = new DefaultHttpClient();
    String json = obj.toString();

    try {//from   w  w  w .jav  a2  s  . c o m
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "application/json");

        StringEntity se = new StringEntity(obj.toString());
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);

        HttpResponse response = client.execute(post);
        String retval = EntityUtils.toString(response.getEntity());

        return new JSONObject(retval);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}