Example usage for org.apache.http.protocol HTTP UTF_8

List of usage examples for org.apache.http.protocol HTTP UTF_8

Introduction

In this page you can find the example usage for org.apache.http.protocol HTTP UTF_8.

Prototype

String UTF_8

To view the source code for org.apache.http.protocol HTTP UTF_8.

Click Source Link

Usage

From source file:com.microsoft.services.msa.TokenRequest.java

/**
 * Performs the Token Request and returns the OAuth server's response.
 *
 * @return The OAuthResponse from the server
 * @throws LiveAuthException if there is any exception while executing the request
 *                           (e.g., IOException, JSONException)
 *//*from ww  w  .ja  v a 2 s  . co m*/
public OAuthResponse execute() throws LiveAuthException {
    final Uri requestUri = mOAuthConfig.getTokenUri();

    final HttpPost request = new HttpPost(requestUri.toString());

    final List<NameValuePair> body = new ArrayList<NameValuePair>();
    body.add(new BasicNameValuePair(OAuth.CLIENT_ID, this.clientId));

    // constructBody allows subclasses to add to body
    this.constructBody(body);

    try {
        final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(body, HTTP.UTF_8);
        entity.setContentType(CONTENT_TYPE);
        request.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        throw new LiveAuthException(ErrorMessages.CLIENT_ERROR, e);
    }

    final HttpResponse response;
    try {
        response = this.client.execute(request);
    } catch (ClientProtocolException e) {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
    } catch (IOException e) {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
    }

    final HttpEntity entity = response.getEntity();
    final String stringResponse;
    try {
        stringResponse = EntityUtils.toString(entity);
    } catch (IOException e) {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
    }

    final JSONObject jsonResponse;
    try {
        jsonResponse = new JSONObject(stringResponse);
    } catch (JSONException e) {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR, e);
    }

    if (OAuthErrorResponse.validOAuthErrorResponse(jsonResponse)) {
        return OAuthErrorResponse.createFromJson(jsonResponse);
    } else if (OAuthSuccessfulResponse.validOAuthSuccessfulResponse(jsonResponse)) {
        return OAuthSuccessfulResponse.createFromJson(jsonResponse);
    } else {
        throw new LiveAuthException(ErrorMessages.SERVER_ERROR);
    }
}

From source file:com.intel.iotkitlib.http.HttpPutTask.java

public CloudResponse doSync(final String url) {
    HttpClient httpClient = new DefaultHttpClient();
    try {//from  w  w  w . jav  a 2s  . co  m
        HttpContext localContext = new BasicHttpContext();
        HttpPut httpPut = new HttpPut(url);

        if (httpBody != null) {
            //setting HTTP body in entity
            StringEntity bodyEntity = new StringEntity(httpBody, "UTF-8");
            httpPut.setEntity(bodyEntity);
        }

        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpPut.addHeader(nvp.getName(), nvp.getValue());
        }

        if (debug) {
            Log.e(TAG, "URI is : " + httpPut.getURI());
            Header[] headers = httpPut.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
            if (httpBody != null) {
                BufferedReader reader123 = new BufferedReader(
                        new InputStreamReader(httpPut.getEntity().getContent(), HTTP.UTF_8));
                StringBuilder builder123 = new StringBuilder();
                for (String line = null; (line = reader123.readLine()) != null;) {
                    builder123.append(line).append("\n");
                }
                Log.e(TAG, "Body is :" + builder123.toString());
            }
        }

        HttpResponse response = httpClient.execute(httpPut, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }

        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }

        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return new CloudResponse(false, cEx.getMessage());
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return new CloudResponse(false, e.getMessage());
    }
}

From source file:com.intel.iotkitlib.http.HttpPostTask.java

public CloudResponse doSync(final String url) {
    HttpClient httpClient = new DefaultHttpClient();
    try {//w ww.j ava2s  .  c  om
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);

        if (httpBody != null) {
            //setting HTTP body in entity
            StringEntity bodyEntity = new StringEntity(httpBody, "UTF-8");
            httpPost.setEntity(bodyEntity);
        }

        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpPost.addHeader(nvp.getName(), nvp.getValue());
        }

        if (debug) {
            Log.e(TAG, "URI is : " + httpPost.getURI());
            Header[] headers = httpPost.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
            if (httpBody != null) {
                BufferedReader reader123 = new BufferedReader(
                        new InputStreamReader(httpPost.getEntity().getContent(), HTTP.UTF_8));
                StringBuilder builder123 = new StringBuilder();
                for (String line = null; (line = reader123.readLine()) != null;) {
                    builder123.append(line).append("\n");
                }
                Log.e(TAG, "Body is :" + builder123.toString());
            }
        }

        HttpResponse response = httpClient.execute(httpPost, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }
        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }

        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return new CloudResponse(false, cEx.getMessage());
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return new CloudResponse(false, e.getMessage());
    }
}

From source file:mobisocial.metrics.MusubiExceptionHandler.java

private void submitException(Throwable ex) throws IOException {
    if (UsageMetrics.CHIRP_REPORTING_ENDPOINT == null) {
        return;//from  www .  ja va 2 s .c o  m
    }
    try {
        HttpClient http = getHttpClient(mContext);
        HttpPost post = new HttpPost(UsageMetrics.CHIRP_REPORTING_ENDPOINT);
        List<NameValuePair> data = new ArrayList<NameValuePair>();
        JSONObject json = jsonForException(mContext, ex, false);
        data.add(new BasicNameValuePair("json", json.toString()));
        post.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));

        HttpResponse response = http.execute(post);
        response.getEntity();
        int status = response.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) {
            throw new IOException("Failed to post message to server. Http code: " + status);
        }
    } catch (ClientProtocolException e) {
        throw new IOException("Protocol exception while posting to server", e);
    }
}

From source file:jp.co.brilliantservice.android.ric.command.HttpController.java

private void doPost(List<Buffer> buffers) {

    StringBuilder b = new StringBuilder();

    for (int i = 0; i < buffers.size(); ++i) {
        Buffer e = buffers.get(i);
        if (i > 0)
            b.append('Z');
        for (int j = e.offset; j < e.count; ++j) {
            b.append(String.format("%02X", e.buffer[j]));
        }//from   ww w. j  a  v a2s. c  o  m
    }

    final String command = b.toString();

    context.runOnUiThread(new Runnable() {

        public void run() {
            Toast toast = Toast.makeText(context, command.toString(), Toast.LENGTH_SHORT);
            toast.show();
        }
    });

    Runnable task = new Runnable() {

        public void run() {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost req = new HttpPost(server);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Log.i("RIC", command);
            nvps.add(new BasicNameValuePair("c", command));
            try {
                req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            } catch (UnsupportedEncodingException e1) {
            }

            try {
                final HttpResponse res = client.execute(req);
                context.runOnUiThread(new Runnable() {
                    public void run() {
                        Toast toast = Toast.makeText(context, res.getStatusLine().toString(),
                                Toast.LENGTH_SHORT);
                        toast.show();
                    }
                });
            } catch (final Exception e) {
                context.runOnUiThread(new Runnable() {
                    public void run() {
                        Toast toast = Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT);
                        toast.show();
                    }
                });
                return;
            }
        }
    };

    exec.execute(task);
}

From source file:com.xabber.android.data.account.WLMManager.java

/**
 * @param protocol//from ww w.  j  a  v  a 2  s  .  co m
 * @param grantType
 * @param value
 * @return Access and refresh tokens or <code>null</code> if auth failed.
 * @throws NetworkException
 */
private OAuthResult accessTokenOperation(GrantType grantType, String value) throws NetworkException {
    HttpPost httpPost = new HttpPost(
            new Uri.Builder().scheme(WLM_SCHEME).authority(WLM_AUTHORITY).path("token").build().toString());
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("grant_type", grantType.name));
    nameValuePairs.add(new BasicNameValuePair(grantType.value, value));
    nameValuePairs.add(new BasicNameValuePair("redirect_uri", WLM_REDIRECT_URL));
    nameValuePairs.add(new BasicNameValuePair("client_id", WLM_CLIENT_ID));
    nameValuePairs.add(new BasicNameValuePair("client_secret", WLM_CLIENT_SECRET));
    UrlEncodedFormEntity encodedFormEntity;
    try {
        encodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
    } catch (UnsupportedEncodingException e) {
        throw new NetworkException(R.string.CONNECTION_FAILED, e);
    }
    String content;
    try {
        content = EntityUtils.toString(encodedFormEntity);
    } catch (ParseException e) {
        throw new NetworkException(R.string.CONNECTION_FAILED, e);
    } catch (IOException e) {
        throw new NetworkException(R.string.CONNECTION_FAILED, e);
    }
    LogManager.i(this, httpPost.getURI().toString() + "\n" + content);
    httpPost.setEntity(encodedFormEntity);
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse httpResponse;
    try {
        httpResponse = httpClient.execute(httpPost);
    } catch (ClientProtocolException e) {
        throw new NetworkException(R.string.CONNECTION_FAILED, e);
    } catch (IOException e) {
        throw new NetworkException(R.string.CONNECTION_FAILED, e);
    }
    HttpEntity entity = httpResponse.getEntity();
    try {
        content = EntityUtils.toString(entity);
    } catch (ParseException e) {
        throw new NetworkException(R.string.CONNECTION_FAILED, e);
    } catch (IOException e) {
        throw new NetworkException(R.string.CONNECTION_FAILED, e);
    } finally {
        try {
            entity.consumeContent();
        } catch (IOException e) {
            throw new NetworkException(R.string.CONNECTION_FAILED, e);
        }
    }
    LogManager.i(this, content);
    long expiresIn;
    String accessToken;
    String refreshToken;
    try {
        JSONObject jsonObject = (JSONObject) new JSONTokener(content).nextValue();
        if (jsonObject.has("error"))
            return null;
        try {
            expiresIn = Long.valueOf(jsonObject.getString("expires_in")) * 1000;
        } catch (NumberFormatException e) {
            throw new NetworkException(R.string.CONNECTION_FAILED, e);
        }
        accessToken = jsonObject.getString("access_token");
        refreshToken = jsonObject.getString("refresh_token");
    } catch (JSONException e) {
        throw new NetworkException(R.string.CONNECTION_FAILED, e);
    }
    return new OAuthResult(accessToken, refreshToken, expiresIn);
}

From source file:org.que.async.AsyncJSONSender.java

@Override
protected List<JSONObject> doInBackground(JSONObject... arg0) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    post.addHeader(CONTENT_TYPE_KEY, CONTENT_TYPE);
    List<JSONObject> result = new ArrayList<JSONObject>();
    if (arg0 != null) {
        for (int i = 0; i < arg0.length; i++) {
            try {
                JSONObject json = arg0[i];
                post.setEntity(new StringEntity(json.toString(), HTTP.UTF_8));
                HttpResponse response = client.execute(post);
                if (response == null || response.getStatusLine().getStatusCode() >= 400) {
                    Log.e(AsyncJSONSender.class.getName(),
                            String.format(ERROR_LOG_MSG, response.getStatusLine().getStatusCode()));
                    job.doExeptionHandling(null);
                } else {
                    HttpEntity entity = response.getEntity();
                    if (entity != null && entity.getContentType().getValue().equals(CONTENT_TYPE)) {
                        try {
                            JSONObject object = new JSONObject(EntityUtils.toString(entity));
                            result.add(object);
                        } catch (JSONException ex) {
                            Log.e(AsyncJSONSender.class.getName(), "JSONObject creation failed", ex);
                        }/*from ww w .j av  a2  s .c  o m*/
                    }
                }
            } catch (ClientProtocolException ex) {
                Log.e(AsyncJSONSender.class.getName(), "Exception", ex);
                job.doExeptionHandling(ex);
            } catch (UnsupportedEncodingException ex) {
                Log.e(AsyncJSONSender.class.getName(), "Exception", ex);
                job.doExeptionHandling(ex);
            } catch (IOException ex) {
                Log.e(AsyncJSONSender.class.getName(), "Exception", ex);
                job.doExeptionHandling(ex);
            }
        }
    }
    return result;
}

From source file:com.shmsoft.dmass.data.index.SolrIndex.java

protected void sendPostCommand(String point, String param) throws SolrException {
    HttpClient httpClient = new DefaultHttpClient();

    try {//w  ww. j  ava2s .c om
        HttpPost request = new HttpPost(point);
        StringEntity params = new StringEntity(param, HTTP.UTF_8);
        params.setContentType("text/xml");

        request.setEntity(params);

        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() != 200) {
            History.appendToHistory("Solr Invalid Response: " + response.getStatusLine().getStatusCode());
        }

    } catch (Exception ex) {
        throw new SolrException("Problem sending request", ex);
    }
}

From source file:vitro.vgw.communication.idas.IdasProxyImpl.java

private Object sendRequest(String request) throws VitroGatewayException {

    Object result = null;//from  w ww  .  ja  va2  s  . com

    InputStream instream = null;

    try {
        HttpPost httpPost = new HttpPost(endPoint);

        StringEntity entityPar = new StringEntity(request, "application/xml", HTTP.UTF_8);

        httpPost.setEntity(entityPar);

        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {

            instream = entity.getContent();

            Unmarshaller unmarshaller = Utils.getJAXBContext().createUnmarshaller();
            Object idasResponse = unmarshaller.unmarshal(instream);

            if (idasResponse instanceof ExceptionReport) {
                throw Utils.parseException((ExceptionReport) idasResponse);
            }

            result = idasResponse;

        } else {
            throw new VitroGatewayException("Server response does not contain any body");
        }
    } catch (VitroGatewayException e) {
        throw e;
    } catch (Exception e) {
        throw new VitroGatewayException(e);
    } finally {
        if (instream != null) {
            try {
                instream.close();
            } catch (IOException e) {
                logger.error("Error while closing server response stream", e);
            }
        }
    }

    return result;

}