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.neu.bigdata.service.PredictionService.java

private String rrsHttpPost() {

    HttpPost post;/*  ww  w.ja  v  a  2 s. c om*/
    HttpClient client;
    StringEntity entity;
    String response = "";

    try {
        // create HttpPost and HttpClient object
        post = new HttpPost(API_URL);
        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 " + API_KEY));
        post.setEntity(entity);

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

        return response;

    } catch (Exception e) {

        return e.toString();
    }

}

From source file:net.java.sip.communicator.impl.protocol.sip.xcap.BaseHttpXCapClient.java

/**
 * Puts the resource to the server.//from ww  w.ja v a 2  s . c om
 *
 * @param resource the resource  to be saved on the server.
 * @return the server response.
 * @throws IllegalStateException if the user has not been connected.
 * @throws XCapException         if there is some error during operation.
 */
public XCapHttpResponse put(XCapResource resource) throws XCapException {
    DefaultHttpClient httpClient = null;
    try {
        httpClient = createHttpClient();

        URI resourceUri = getResourceURI(resource.getId());
        HttpPut putMethod = new HttpPut(resourceUri);
        putMethod.setHeader("Connection", "close");
        StringEntity stringEntity = new StringEntity(resource.getContent());
        stringEntity.setContentType(resource.getContentType());
        stringEntity.setContentEncoding("UTF-8");
        putMethod.setEntity(stringEntity);

        if (logger.isDebugEnabled()) {
            String logMessage = String.format("Puting resource %1s to the server %2s",
                    resource.getId().toString(), resource.getContent());
            logger.debug(logMessage);
        }
        HttpResponse response = httpClient.execute(putMethod);
        return createResponse(response);
    } catch (IOException e) {
        String errorMessage = String.format("%1s resource cannot be put", resource.getId().toString());
        throw new XCapException(errorMessage, e);
    } finally {
        if (httpClient != null)
            httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.mozilla.simplepush.simplepushdemoapp.MainActivity.java

/** Send the registration id to the Push Server.
 *
 * Prior versions used a websocket based protocol to exchange this information. This
 * meant that android libraries had to bring in a websocket protocol dependency (see previous
 * versions of this code). This requirement was removed.
 *
 * @param regid GCM Registration ID//from ww w. j  av  a 2s .c o m
 */
private void sendRegistrationIdToBackend(final String regid) {
    String target = getTarget();
    Log.i(TAG, "Sending out Regid " + regid + " to " + target);
    JSONObject msg = new JSONObject();
    try {
        JSONObject token = new JSONObject();
        msg.put("type", "gcm");
        msg.put("channelID", CHANNEL_ID);
        token.put("token", regid);
        msg.put("data", token);
    } catch (JSONException x) {
        this.err("Could not send registration " + x.toString());
        return;
    }
    HttpPost req = new HttpPost(target);
    try {
        StringEntity body = new StringEntity(msg.toString());
        body.setContentType("application/json");
        body.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "text/plain; charset=UTF-8"));
        req.setEntity(body);
    } catch (UnsupportedEncodingException x) {
        this.err("Could not format registration message " + x.toString());
        return;
    }
    try {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse resp = client.execute(req);
        int code = resp.getStatusLine().getStatusCode();
        if (code < 200 || code > 299) {
            this.err("Server failed to accept message " + EntityUtils.toString(resp.getEntity()));
            return;
        }
        try {
            JSONObject reply = new JSONObject(new JSONTokener(EntityUtils.toString(resp.getEntity())));
            if (!this.CHANNEL_ID.equals(reply.getString("channelID"))) {
                this.err("Recieved inappropriate registration info: " + resp.getEntity().toString());
                return;
            }
            this.PushEndpoint = reply.getString("endpoint");
            this.UserAgentID = reply.getString("uaid");
            this.SharedSecret = reply.getString("secret");
        } catch (JSONException x) {
            this.err("Could not parse registration info " + x.toString());
        }
    } catch (IOException x) {
        this.err("Could not send registration " + x.toString());
    }
}

From source file:org.exfio.weave.storage.StorageContext.java

public Double put(URI location, WeaveBasicObject wbo) throws WeaveException {
    Log.getInstance().debug("put()");

    Double modified = null;//from w ww . java2  s.  c om

    HttpPut put = new HttpPut(location);
    CloseableHttpResponse response = null;

    try {
        //Backwards compatible with android version of org.apache.http
        StringEntity entityPut = new StringEntity(encodeWeaveBasicObject(wbo));
        entityPut.setContentType("text/plain");
        entityPut.setContentEncoding("UTF-8");

        put.setEntity(entityPut);

        response = httpClient.execute(put);
        checkResponse(response);

        //parse request content to extract server modified time
        modified = parseModifiedResponse(EntityUtils.toString(response.getEntity()));

    } catch (IOException e) {
        throw new WeaveException(e);
    } catch (HttpException e) {
        throw new WeaveException(e);
    } catch (GeneralSecurityException e) {
        throw new WeaveException(e);
    } finally {
        closeResponse(response);
    }

    return modified;
}

From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java

@Test
public void testPut() throws Exception {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPut httpPut = new HttpPut(
            "https://xs01ca06b6163.ap1.hana.ondemand.com/jncpf2/wsb01.xsodata/WineSmallProduction('5BCA672AA43184D2B242BE2749B54B13')");
    httpPut.addHeader("Content-Type", "application/json;charset=UTF-8");
    HttpContext httpContext = new BasicHttpContext();

    JSONObject jsonParam = new JSONObject();
    jsonParam.put("containerID", "45F72A9B1873CBAC87322769D594DAB7");
    jsonParam.put("boxID", "DFE74C483C4D9AB51CEC8AE1FBFACC9F");
    jsonParam.put("bottleEID", "448F881AECF7647331AEF66D996173BE");
    jsonParam.put("bottleIID", "3FF40C650FEA476DACB3ED3A9764929E");
    jsonParam.put("bottleVID", "EE410D11");
    jsonParam.put("status", 6);

    StringEntity entity = new StringEntity(jsonParam.toString(), "UTF-8");// ?
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");

    httpPut.setEntity(entity);/*  w w w .  jav a 2  s .c  o  m*/

    HttpResponse response = httpClient.execute(httpPut, httpContext);

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();

    System.out.println(statusCode);
}

From source file:com.prey.net.PreyWebServices.java

public void postData(String url, JSONObject obj) {

    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    HttpClient httpclient = new DefaultHttpClient(myParams);
    String json = obj.toString();

    try {/*from   w w w . ja  va2 s  .co  m*/

        HttpPost httppost = new HttpPost(url.toString());
        httppost.setHeader("Content-type", "application/json");

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

        HttpResponse response = httpclient.execute(httppost);
        String temp = EntityUtils.toString(response.getEntity());
        PreyLogger.d("tag" + temp);

    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }
}

From source file:com.kdao.cmpe235_project.UploadActivity.java

private void addUploadedFIleToDB(final String APIurl, String treeId, String fileName) {
    class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
        @Override//from www .  j  a  v  a  2s .  c om
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(UploadActivity.this, "", Config.SAVE_TO_DB);
        }

        @Override
        protected String doInBackground(String... params) {
            String uploadFileName = params[0];
            String treeId = params[1];
            String APIurl = params[2];
            HttpClient httpClient = new DefaultHttpClient();
            HttpPut httpPut = new HttpPut(Config.BASE_URL + APIurl);
            org.json.JSONObject json = new org.json.JSONObject();
            try {
                json.put("filename", uploadFileName);
                json.put("treeId", treeId);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                StringEntity se = new StringEntity(json.toString());
                se.setContentEncoding("UTF-8");
                httpPut.setEntity(se);
                try {
                    HttpResponse httpResponse = httpClient.execute(httpPut);
                    InputStream inputStream = httpResponse.getEntity().getContent();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    StringBuilder stringBuilder = new StringBuilder();
                    String bufferedStrChunk = null;
                    while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
                        stringBuilder.append(bufferedStrChunk);
                    }
                    return stringBuilder.toString();
                } catch (Exception e) {
                    System.out
                            .println("An Exception given because of UrlEncodedFormEntity " + "argument :" + e);
                    e.printStackTrace();
                }
            } catch (Exception uee) {
                System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
                uee.printStackTrace();
            }
            return "error";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progressDialog.dismiss();
            if (result == "error") { //error case
                Toast.makeText(getApplicationContext(), Config.SERVER_ERR, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), Config.DB_WRITE_SUCCEED, Toast.LENGTH_LONG).show();
            }
        }
    }
    SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
    sendPostReqAsyncTask.execute(fileName, treeId, APIurl);
}

From source file:com.algolia.search.saas.APIClient.java

private JSONObject _requestByHost(HttpRequestBase req, String host, String url, String json,
        HashMap<String, String> errors) throws AlgoliaException {
    req.reset();/*from   w ww.  ja v a2  s  .c o  m*/

    // set URL
    try {
        req.setURI(new URI("https://" + host + url));
    } catch (URISyntaxException e) {
        // never reached
        throw new IllegalStateException(e);
    }

    // set auth headers
    req.setHeader("X-Algolia-Application-Id", this.applicationID);
    if (forwardAdminAPIKey == null) {
        req.setHeader("X-Algolia-API-Key", this.apiKey);
    } else {
        req.setHeader("X-Algolia-API-Key", this.forwardAdminAPIKey);
        req.setHeader("X-Forwarded-For", this.forwardEndUserIP);
        req.setHeader("X-Forwarded-API-Key", this.forwardRateLimitAPIKey);
    }
    for (Entry<String, String> entry : headers.entrySet()) {
        req.setHeader(entry.getKey(), entry.getValue());
    }

    // set user agent
    req.setHeader("User-Agent", "Algolia for Java " + version);

    // set JSON entity
    if (json != null) {
        if (!(req instanceof HttpEntityEnclosingRequestBase)) {
            throw new IllegalArgumentException("Method " + req.getMethod() + " cannot enclose entity");
        }
        req.setHeader("Content-type", "application/json");
        try {
            StringEntity se = new StringEntity(json, "UTF-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            ((HttpEntityEnclosingRequestBase) req).setEntity(se);
        } catch (UnsupportedEncodingException e) {
            throw new AlgoliaException("Invalid JSON Object: " + json); // $COVERAGE-IGNORE$
        }
    }

    RequestConfig config = RequestConfig.custom().setSocketTimeout(httpSocketTimeoutMS)
            .setConnectTimeout(httpConnectTimeoutMS).setConnectionRequestTimeout(httpConnectTimeoutMS).build();
    req.setConfig(config);

    HttpResponse response;
    try {
        response = httpClient.execute(req);
    } catch (IOException e) {
        // on error continue on the next host
        errors.put(host, String.format("%s=%s", e.getClass().getName(), e.getMessage()));
        return null;
    }
    try {
        int code = response.getStatusLine().getStatusCode();
        if (code / 100 == 4) {
            String message = "";
            try {
                message = EntityUtils.toString(response.getEntity());
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (code == 400) {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Bad request");
            } else if (code == 403) {
                throw new AlgoliaException(code,
                        message.length() > 0 ? message : "Invalid Application-ID or API-Key");
            } else if (code == 404) {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Resource does not exist");
            } else {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Error");
            }
        }
        if (code / 100 != 2) {
            try {
                errors.put(host, EntityUtils.toString(response.getEntity()));
            } catch (IOException e) {
                errors.put(host, String.valueOf(code));
            }
            // KO, continue
            return null;
        }
        try {
            InputStream istream = response.getEntity().getContent();
            InputStreamReader is = new InputStreamReader(istream, "UTF-8");
            JSONTokener tokener = new JSONTokener(is);
            JSONObject res = new JSONObject(tokener);
            is.close();
            return res;
        } catch (IOException e) {
            return null;
        } catch (JSONException e) {
            throw new AlgoliaException("JSON decode error:" + e.getMessage());
        }
    } finally {
        req.releaseConnection();
    }
}

From source file:de.stklcode.jvault.connector.HTTPVaultConnector.java

/**
 * Execute HTTP request using POST method.
 *
 * @param path    URL path (relative to base)
 * @param payload Map of payload values (will be converted to JSON)
 * @return HTTP response/*from   w  ww .j  a  v a  2  s.  co m*/
 * @throws VaultConnectorException on connection error
 */
private String requestPost(final String path, final Object payload) throws VaultConnectorException {
    /* Initialize post */
    HttpPost post = new HttpPost(baseURL + path);
    /* generate JSON from payload */
    StringEntity input;
    try {
        input = new StringEntity(jsonMapper.writeValueAsString(payload), StandardCharsets.UTF_8);
    } catch (JsonProcessingException e) {
        throw new InvalidRequestException(Error.PARSE_RESPONSE, e);
    }
    input.setContentEncoding("UTF-8");
    input.setContentType("application/json");
    post.setEntity(input);
    /* Set X-Vault-Token header */
    if (token != null)
        post.addHeader(HEADER_VAULT_TOKEN, token);

    return request(post, retries);
}

From source file:com.corebase.android.framework.http.client.AsyncHttpClient.java

/**
 * Jsonpost//from  w ww.ja v a 2s.  com
 * 
 * @param context
 * @param url
 * @param cacheParams
 * @param params
 * @param responseHandler
 * @throws UnsupportedEncodingException
 */
public void postToJsonParam(Context context, String url, CacheParams cacheParams, String jsonString,
        String requestParam, AsyncHttpResponseHandler responseHandler) throws UnsupportedEncodingException {
    StringEntity stringEntity = new StringEntity(jsonString, "UTF-8");
    stringEntity.setContentEncoding("UTF-8");
    stringEntity.setContentType("application/json");
    postToCache(context, url, stringEntity, cacheParams, null, responseHandler, requestParam);
}