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.ab.http.AbRequestParams.java

/**
 * ??.
 * @return the param string
 */
public String getParamString() {
    return URLEncodedUtils.format(getParamsList(), HTTP.UTF_8);
}

From source file:com.android.wako.net.AsyncHttpPost.java

public boolean process() {
    try {//from   ww  w. j  a v  a2  s .co  m
        //            LogUtil.d(Tag, "---process---url="+url+"?"+getParames());
        request = new HttpPost(url);
        if (Constants.isGzip) {
            request.addHeader("Accept-Encoding", "gzip");
        } else {
            request.addHeader("Accept-Encoding", "default");
        }
        request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        //            LogUtil.d(AsyncHttpPost.class.getName(),
        //                    "AsyncHttpPost  request to url :" + url);

        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));
        }
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // ??
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset??
            bis.reset();
            // ?GZIP?
            int headerData = getShort(header);
            // Gzip ? ? 0x1f8b
            if (result != -1 && headerData == 0x1f8b) {
                LogUtil.d("HttpTask", " use GZIPInputStream  ");
                is = new GZIPInputStream(bis);
            } else {
                LogUtil.d("HttpTask", " not use GZIPInputStream");
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            ret = sb.toString();
            bis.close();
            reader.close();
            return true;

        } else {
            mRetStatus = ResStatus.Error_Code;
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "??,??" + statusCode);
            //                ret = ErrorUtil.errorJson("ERROR.HTTP.001",
            //                        exception.getMessage());
        }

        LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost  request to url :" + url + "  finished !");
    } catch (IllegalArgumentException e) {
        mRetStatus = ResStatus.Error_IllegalArgument;
        //            RequestException exception = new RequestException(
        //                    RequestException.IO_EXCEPTION, Constants.ERROR_MESSAGE);
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.002", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        mRetStatus = ResStatus.Error_Connect_Timeout;
        //            RequestException exception = new RequestException(
        //                    RequestException.SOCKET_TIMEOUT_EXCEPTION, Constants.ERROR_MESSAGE);
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.003", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        mRetStatus = ResStatus.Error_Socket_Timeout;
        //            RequestException exception = new RequestException(
        //                    RequestException.SOCKET_TIMEOUT_EXCEPTION, Constants.ERROR_MESSAGE);
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.004", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        mRetStatus = ResStatus.Error_Unsupport_Encoding;
        e.printStackTrace();
        //            RequestException exception = new RequestException(
        //                    RequestException.UNSUPPORTED_ENCODEING_EXCEPTION, "?");
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.005", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  UnsupportedEncodingException  " + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        mRetStatus = ResStatus.Error_HttpHostConnect;
        e.printStackTrace();
        //            RequestException exception = new RequestException(
        //                    RequestException.CONNECT_EXCEPTION, "");
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.006", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        mRetStatus = ResStatus.Error_Client_Protocol;
        e.printStackTrace();
        //            RequestException exception = new RequestException(
        //                    RequestException.CLIENT_PROTOL_EXCEPTION, "??");
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        mRetStatus = ResStatus.Error_IOException;
        //            RequestException exception = new RequestException(
        //                    RequestException.IO_EXCEPTION, "??");
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.008", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  IOException  " + e.getMessage());
    } catch (Exception e) {
        mRetStatus = ResStatus.Error_IOException;
        e.printStackTrace();
    }
    return false;
}

From source file:com.taqueue.connection.QueueConnectionManager.java

/**
 * Sends a POST to the queue with the parameters nvps, returns the result.
 * @param nvps the NameValuePair of parameters to be sent to the queue server
 * @return ConnectionResult containing the status code for the attempt and the message returned
 * message will be null iff the status is not OK
 *//*  ww  w.  j  a va  2 s. co m*/
private ConnectionResult sendMessage(List<NameValuePair> nvps) {
    ConnectionResult res = new ConnectionResult();
    //default to OK, we'll change in the event of an error
    res.status = ConnectionStatus.OK;
    HttpPost post = new HttpPost(HOST + PATH);
    //DefaultHttpClient client = new DefaultHttpClient();
    //set up the timeout
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT);
    // set up the connection manager if needed
    if (manager == null) {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        manager = new ThreadSafeClientConnManager(httpParams, registry);
    }
    DefaultHttpClient client = new DefaultHttpClient(manager, httpParams);
    try {
        //set up our POST values
        post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        //send it along
        ResponseHandler<String> handler = new BasicResponseHandler();
        connectionWatcher watcher = new connectionWatcher(post);
        Thread t = new Thread(watcher);
        t.start();
        res.message = client.execute(post, handler);
        watcher.finished();
        //and clean up
        //if any exceptions are thrown return a connection error result
    } catch (Exception e) {
        res.status = ConnectionStatus.CONNECTION_ERROR;
        res.message = null;
    } finally {
        post.abort();
    }
    return res;
}

From source file:magicware.scm.redmine.tools.RedmineClient.java

public String createNewIssue(String newIssue) throws ClientProtocolException, IOException {
    HttpPost httpPost = null;//from   w  w  w.j a  v a  2 s  .  co  m
    String newIssueId = null;
    try {
        log.trace(newIssue);
        httpPost = new HttpPost(this.context + "/issues.json");
        httpPost.setEntity(new StringEntity(newIssue, "application/json", HTTP.UTF_8));
        log.debug("executing post request " + httpPost.getURI());

        // ???
        RdeminResponse rdeminResponse = getRdeminResponse(httpPost);

        if (rdeminResponse.isResponseOK()) {
            Matcher m = Pattern.compile(Constants.ISSUE_ID_VALUE_EXP).matcher(rdeminResponse.getContent());
            while (m.find()) {
                MatchResult mr = m.toMatchResult();
                newIssueId = mr.group(1).trim();
            }
        }
        return newIssueId;

    } finally {
        if (httpPost != null)
            httpPost.abort();
    }
}

From source file:com.deliciousdroid.client.NetworkUtilities.java

/**
 * Gets the title of a web page./*from w  ww.j  a  va  2 s. c o m*/
 * 
 * @param url The URL of the web page.
 * @return A String containing the title of the web page.
 */
public static String getWebpageTitle(String url) {

    if (url != null && !url.equals("")) {

        if (!url.startsWith("http")) {
            url = "http://" + url;
        }

        HttpResponse resp = null;
        HttpGet post = null;

        try {
            post = new HttpGet(url.replace("|", "%7C"));

            post.setHeader("User-Agent", "Mozilla/5.0");

            resp = HttpClientFactory.getThreadSafeClient().execute(post);

            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String response = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
                int start = response.indexOf("<title>") + 7;
                int end = response.indexOf("</title>", start + 1);
                String title = response.substring(start, end);
                return title;
            } else
                return "";
        } catch (Exception e) {
            return "";
        }
    } else
        return "";
}

From source file:org.dasein.cloud.aws.platform.CloudFrontMethod.java

protected @Nonnull HttpClient getClient(String url) throws InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new InternalException("No context was specified for this request");
    }/* w w  w  .  j ava  2 s. c o m*/
    boolean ssl = url.startsWith("https");
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    return new DefaultHttpClient(params);
}

From source file:com.wms.ezyoukuuploader.sdk.activity.GetRefreshTokenActivity.java

private String getRefreshToken() {

    Thread t = new Thread(new Runnable() {

        @SuppressWarnings("deprecation")
        @Override//from   w w w. j a  va 2s. c  om
        public void run() {
            HttpPost httpPost = new HttpPost(YoukuConstants.YOUKU_OAUTH2_URL);
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair(YoukuConstants.PARAM_CLIENT_ID,
                    getString(R.string.YOUKU_APP_CLIENT_ID)));
            params.add(new BasicNameValuePair(YoukuConstants.PARAM_CLIENT_SECRET,
                    getString(R.string.YOUKU_APP_CLIENT_SECRET)));
            params.add(new BasicNameValuePair(YoukuConstants.PARAM_GRANT_TYPE,
                    YoukuConstants.GRANT_TYPE_AUTHORIZATION_CODE));
            params.add(new BasicNameValuePair(YoukuConstants.PARAM_AUTHORIZATION_CODE, authorizationCode));
            params.add(new BasicNameValuePair(YoukuConstants.PARAM_REDIRECT_URI,
                    getString(R.string.YOUKU_APP_REDIRECT_URI)));
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    String result = EntityUtils.toString(httpResponse.getEntity());
                    JSONObject object = new JSONObject(result);
                    accessToken = object.getString(YoukuConstants.PARAM_ACCESS_TOKEN);
                    refreshToken = object.getString(YoukuConstants.PARAM_REFRESH_TOKEN);
                    SharedPreferenceUtil.savePreferenceItemByName(GetRefreshTokenActivity.this,
                            SharedPreferenceUtil.YoukuAccessToken, accessToken);
                    SharedPreferenceUtil.savePreferenceItemByName(GetRefreshTokenActivity.this,
                            SharedPreferenceUtil.YoukuRefreshToken, refreshToken);
                }
            } catch (Exception e) {
                // refreshToken remains null. No need to do anything
            }
        }

    });

    t.start();
    try {
        t.join();
    } catch (InterruptedException e) {
        // refreshToken remains null. No need to do anything
    }

    return refreshToken;
}

From source file:com.am.rest.RestServiceClient.java

/**
 * Posts string data to the given URL. This call blocks until the operation
 * has completed.// ww  w.j  a  v a 2 s  .c  o  m
 * 
 * @param url
 *            The exact URL to request.
 * @param body
 *            String content.
 * @return The raw content returned by the server.
 * @throws RestException
 *             If any connection or server error occurs.
 */
public String post(String url, String body) throws RestException {
    try {
        HttpPost request = new HttpPost(url);
        request.setEntity(new StringEntity(body, HTTP.UTF_8));
        HttpResponse response = execute(request);
        return getPlainContent(response);
    } catch (IOException e) {
        throw new RestException("POST failed with the REST web service", e);
    }
}

From source file:de.escidoc.core.test.aa.UserGroupTestBase.java

/**
 * Test deactivating an UserGroup.//from  ww w. j av a 2 s.com
 *
 * @param id           The id of the UserGroup.
 * @param taskParamXml The task parameter in an XML structure.
 * @return userGroup-XML
 * @throws Exception If anything fails.
 */
protected String deactivate(final String id, final String taskParamXml) throws Exception {

    Object result = getUserGroupClient().deactivate(id, taskParamXml);
    String xmlResult = null;
    if (result instanceof HttpResponse) {
        HttpResponse method = (HttpResponse) result;
        xmlResult = EntityUtils.toString(method.getEntity(), HTTP.UTF_8);
        assertHttpStatusOfMethod("", method);

        if (xmlResult.equals("")) {
            xmlResult = null;
        }
    } else if (result instanceof String) {
        xmlResult = (String) result;
    }
    return xmlResult;
}

From source file:de.escidoc.core.test.aa.UserPreferenceTestBase.java

protected String retrievePreferences(final String id) throws Exception {

    Object result = client.retrievePreferences(id);
    String xmlResult = null;//from   ww w.j  av a2s.  c o m
    if (result instanceof HttpResponse) {
        HttpResponse method = (HttpResponse) result;
        xmlResult = EntityUtils.toString(method.getEntity(), HTTP.UTF_8);
        assertHttpStatusOfMethod("", method);
    } else if (result instanceof String) {
        xmlResult = (String) result;
    }
    return xmlResult;
}