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:Main.java

/**
 * Encode/escape www-url-form-encoded content.
 * <p/>//w  w  w  .j ava  2  s .  c  om
 * Uses the {@link #URLENCODER} set of characters, rather than
 * the set; this is for compatibilty with previous
 * releases, URLEncoder.encode() and most browsers.
 *
 * @param content the content to encode, will convert space to '+'
 * @param charset the charset to use
 * @return encoded string
 */
private static String encodeFormFields(final String content, final String charset) {
    if (content == null) {
        return null;
    }
    return urlencode(content, charset != null ? Charset.forName(charset) : Charset.forName(HTTP.UTF_8),
            URLENCODER, true);
}

From source file:com.halzhang.android.apps.startupnews.snkit.SNApi.java

/**
 * /*ww  w. ja  v a2s  .  c o  m*/
 * 
 * @param fnid
 * @param text
 * @param responseHandler
 */
public void comment(Context context, String fnid, String text, AsyncHttpResponseHandler responseHandler) {
    ArrayList<NameValuePair> valuePairs = new ArrayList<NameValuePair>(2);
    valuePairs.add(new BasicNameValuePair("fnid", fnid));
    valuePairs.add(new BasicNameValuePair("text", text));
    try {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, HTTP.UTF_8);
        mAsyncHttpClient.post(context, context.getString(R.string.host, "/r"), entity,
                "application/x-www-form-urlencoded", responseHandler);
    } catch (UnsupportedEncodingException e) {
        CDLog.e(LOG_TAG, e.getMessage());
    }
}

From source file:org.niceday.AsyncHttpPost.java

@Override
public void run() {
    try {//www.  j a v a2s . co m
        request = new HttpPost(url);
        Log.d(AsyncHttpPost.class.getName(), "AsyncHttpGet  request to url :" + url);
        request.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        request.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
        if (parameter != null && parameter.size() > 0) {
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            for (RequestParameter p : parameter) {
                list.add(new BasicNameValuePair(p.getName(), p.getValue()));
            }
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        }
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            ByteArrayOutputStream content = new ByteArrayOutputStream();
            response.getEntity().writeTo(content);
            String ret = new String(content.toByteArray()).trim();
            content.close();
            Object Object = null;
            if (AsyncHttpPost.this.handler != null) {
                Object = AsyncHttpPost.this.handler.handle(ret);
                if (AsyncHttpPost.this.requestCallback != null && Object != null) {
                    AsyncHttpPost.this.requestCallback.onSuccess(Object);
                    return;
                }
                if (Object == null || "".equals(Object.toString())) {
                    RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                            "");
                    AsyncHttpPost.this.requestCallback.onFail(exception);
                }
            } else {
                AsyncHttpPost.this.requestCallback.onSuccess(ret);
            }
        } else {
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "," + statusCode);
            AsyncHttpPost.this.requestCallback.onFail(exception);
        }

        Log.d(AsyncHttpPost.class.getName(), "AsyncHttpGet  request to url :" + url + "  finished !");
    } catch (java.lang.IllegalArgumentException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpGet.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION,
                "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  UnsupportedEncodingException  " + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION, "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION,
                "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        e.printStackTrace();
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        e.printStackTrace();
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  IOException  " + e.getMessage());
    } finally {
        //request.
    }
    super.run();
}

From source file:com.qingzhi.apps.fax.client.NetworkUtilities.java

private static String executeGet(String url, Map<String, String> map) throws IOException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpParams params = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, HTTP_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, HTTP_SO_TIMEOUT);

    HttpPost post = new HttpPost(url);

    ArrayList<BasicNameValuePair> postDate = new ArrayList<BasicNameValuePair>();
    Set<String> set = map.keySet();
    Iterator<String> iterator = set.iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        postDate.add(new BasicNameValuePair(key, map.get(key)));
    }/*from   ww  w  .  j a  v a2s. c  o m*/
    post.setEntity(new UrlEncodedFormEntity(postDate, HTTP.UTF_8));
    HttpResponse httpResponse = httpclient.execute(post);
    throwErrors(httpResponse);

    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        String response = EntityUtils.toString(httpEntity);
        LOGD(TAG, response);
        return response;
    }
    return null;
}

From source file:com.mockey.storage.xml.MockeyXmlFactory.java

private String getDocumentAsString(Document document) throws IOException, TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, HTTP.UTF_8);
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(document);
    transformer.transform(source, result);
    return result.getWriter().toString();
}

From source file:cn.sharesdk.analysis.net.NetworkHelper.java

public static PostResult post(String url, String data, String appkey) {

    //Ln.i(" post msg url ==>>", url);
    //Ln.i(" post msg appkey ==>>", appkey);

    PostResult postResult = new PostResult();
    if (TextUtils.isEmpty(appkey)) {
        postResult.setSuccess(false);//from   w w w  . j  av a  2  s . co  m
        postResult.setResponseMsg("appkey is null");
        return postResult;
    }
    HttpPost httppost = new HttpPost(url);
    HttpClient httpclient = new DefaultHttpClient();
    try {
        Ln.i("postdata before base64gizp", "client_data:" + data);

        ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("appkey", appkey));
        if (!TextUtils.isEmpty(data)) {
            data = Base64Gzip(data);
            pairs.add(new BasicNameValuePair("m", data));
        }
        HttpEntity entity = new UrlEncodedFormEntity(pairs, HTTP.UTF_8);
        httppost.addHeader("charset", HTTP.UTF_8);
        httppost.setHeader("Accept", "application/json,text/x-json,application/jsonrequest,text/json");
        httppost.setEntity(entity);

        HttpResponse response = httpclient.execute(httppost);
        int status = response.getStatusLine().getStatusCode();

        String resString = EntityUtils.toString(response.getEntity());
        postResult = parse(status, resString);

    } catch (Exception e) {
        Ln.e("NetworkHelper", "=== post Ln ===", e);
    }
    return postResult;
}

From source file:com.googlecode.noweco.webmail.portal.lotuslive.LotusLivePortalConnector.java

public PortalConnection connect(final HttpHost proxy, final String user, final String password)
        throws IOException {
    DefaultHttpClient httpclient = UnsecureHttpClientFactory.INSTANCE.createUnsecureHttpClient(proxy);

    HttpGet httpGet;/*from  ww w. j a v a2s .  c  o m*/
    HttpPost httpost;
    HttpResponse rsp;
    HttpEntity entity;

    // STEP 1 : Login page

    httpGet = new HttpGet("https://apps.lotuslive.com/manage/account/dashboardHandler/input");
    rsp = httpclient.execute(httpGet);

    entity = rsp.getEntity();
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    // STEP 2 : Send form

    // prepare the request
    httpost = new HttpPost("https://apps.lotuslive.com/pkmslogin.form");
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("login-form-type", "pwd"));
    nvps.add(new BasicNameValuePair("username", user));
    nvps.add(new BasicNameValuePair("password", password));
    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    // send the request
    rsp = httpclient.execute(httpost);

    // free result resources
    entity = rsp.getEntity();
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    int statusCode = rsp.getStatusLine().getStatusCode();
    if (statusCode != 302) {
        throw new IOException("Unable to connect to lotus live portail, status code : " + statusCode);
    }

    // STEP 3 : Fetch SAML token

    httpGet = new HttpGet("https://mail.lotuslive.com/mail/loginlanding");
    rsp = httpclient.execute(httpGet);

    entity = rsp.getEntity();
    String firstEntity = EntityUtils.toString(entity);
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    // STEP 4 : Use SAML token to identify

    httpost = new HttpPost("https://mail.lotuslive.com/auth/tfim");
    nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("TARGET", "http://mail.lotuslive.com/mail"));
    Matcher samlMatcher = SAML_RESPONSE.matcher(firstEntity);
    if (!samlMatcher.find()) {
        throw new IOException("Unable to find SAML token");
    }
    nvps.add(new BasicNameValuePair("SAMLResponse", samlMatcher.group(1)));

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    // send the request
    rsp = httpclient.execute(httpost);

    entity = rsp.getEntity();
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    // STEP 5 : VIEW ROOT PAGE (TODO can delete ?)

    httpGet = new HttpGet("https://mail-usw.lotuslive.com/mail/mail/listing/INBOX");
    rsp = httpclient.execute(httpGet);

    entity = rsp.getEntity();
    if (entity != null) {
        EntityUtils.consume(entity);
    }

    return new DefaultPortalConnection(httpclient, new HttpHost("mail-usw.lotuslive.com", 443), "");
}

From source file:org.lol.reddit.cache.CacheDownload.java

public CacheDownload(final CacheRequest initiator, final CacheManager manager,
        final PrioritisedDownloadQueue queue) {

    this.mInitiator = initiator;

    this.manager = manager;
    this.mQueue = queue;

    if (!initiator.setDownload(this)) {
        cancel();/* w w w . j a  v a  2  s. c om*/
    }

    if (initiator.requestSession != null) {
        session = initiator.requestSession;
    } else {
        session = UUID.randomUUID();
    }

    if (mInitiator.postFields != null) {
        final HttpPost httpPost = new HttpPost(mInitiator.url);
        mHttpRequest = httpPost;
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(mInitiator.postFields, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            BugReportActivity.handleGlobalError(initiator.context, e);
        }

    } else {
        mHttpRequest = new HttpGet(mInitiator.url);
    }
}

From source file:com.zekke.services.http.JsonRequestBuilder.java

public <T> T callForResult(Class<T> resultType) throws RequestException {
    String json = null;//from ww w  . ja  v  a 2s  .c  o  m

    try {
        setUpHeaders();
        setUpFormParams();
        Log.d(TAG, "URL: " + request.getURI());
        HttpResponse response = httpClient.execute(request);
        Log.d(TAG, "Status code: " + response.getStatusLine().getStatusCode());
        HttpEntity entity = response.getEntity();
        json = entity != null ? EntityUtils.toString(entity, HTTP.UTF_8) : null;
        if ((response.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED)
                && !StringUtils.isNullOrBlank(json)) {
            return new Gson().fromJson(json, resultType);
        }
    } catch (ClientProtocolException ex) {
        Log.e(TAG, "Developer bug :(", ex);
        throw new RequestException.Builder().setMessageResource(R.string.http_protocol_error).setErrorType(ex)
                .build();
    } catch (SocketTimeoutException ex) {
        Log.e(TAG, "Timeout", ex);
        throw new RequestException.Builder().setMessageResource(R.string.timeout_error).setErrorType(ex)
                .build();
    } catch (ConnectTimeoutException ex) {
        Log.e(TAG, "Timeout", ex);
        throw new RequestException.Builder().setMessageResource(R.string.timeout_error).setErrorType(ex)
                .build();
    } catch (UnsupportedEncodingException ex) {
        Log.e(TAG, "Developer bug :(", ex);
        throw new RequestException.Builder().setMessageResource(R.string.params_encoding_error).setErrorType(ex)
                .build();
    } catch (IOException ex) {
        Log.e(TAG, "Developer bug :(", ex);
        throw new RequestException.Builder().setMessageResource(R.string.unknown_error).setErrorType(ex)
                .build();
    } catch (JsonSyntaxException ex) {
        Log.e(TAG, "Developer bug :(", ex);
        throw new RequestException.Builder().setMessageResource(R.string.unknown_error).setErrorType(ex)
                .build();
    } catch (ParseException ex) {
        Log.e(TAG, "Developer bug :(", ex);
        throw new RequestException.Builder().setMessageResource(R.string.parse_response_error).setErrorType(ex)
                .build();
    } catch (Exception ex) {
        Log.e(TAG, "Developer bug :(", ex);
        throw new RequestException.Builder().setMessageResource(R.string.unknown_error).setErrorType(ex)
                .build();
    }

    if (!StringUtils.isNullOrBlank(json)) {
        Log.e(TAG, "Server error: " + json);
        try {
            throw new Gson().fromJson(json, RequestException.class);
        } catch (JsonSyntaxException ex) {
            throw new RequestException.Builder().setMessageResource(R.string.unknown_error).setErrorType(ex)
                    .build();
        }
    }

    return null;
}

From source file:com.imaginary.home.controller.CloudService.java

static private @Nonnull HttpClient getClient(@Nonnull String endpoint, @Nullable String proxyHost,
        int proxyPort) {
    boolean ssl = endpoint.startsWith("https");
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "Imaginary Home");

    if (proxyHost != null) {
        if (proxyPort < 0) {
            proxyPort = 0;/* ww  w .j ava 2  s . c  o  m*/
        }
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                new HttpHost(proxyHost, proxyPort, ssl ? "https" : "http"));
    }
    return new DefaultHttpClient(params);
}