Example usage for org.apache.http.params HttpProtocolParams setContentCharset

List of usage examples for org.apache.http.params HttpProtocolParams setContentCharset

Introduction

In this page you can find the example usage for org.apache.http.params HttpProtocolParams setContentCharset.

Prototype

public static void setContentCharset(HttpParams httpParams, String str) 

Source Link

Usage

From source file:playn.http.HttpAndroid.java

@Override
protected void doSend(final HttpRequest request, final Callback<HttpResponse> callback) {
    platform.invokeAsync(new Runnable() {
        public void run() {
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
            HttpProtocolParams.setHttpElementCharset(params, HTTP.UTF_8);
            HttpClient httpclient = new DefaultHttpClient(params);
            HttpRequestBase req;//from  w ww  . ja v a  2 s  .c  o m
            HttpMethod method = request.getMethod();
            String url = request.getUrl();
            switch (method) {
            case GET:
                req = new HttpGet(url);
                break;
            case POST:
                req = new HttpPost(url);
                break;
            case PUT:
                req = new HttpPut(url);
                break;
            default:
                throw new UnsupportedOperationException(method.toString());
            }
            String requestBody = request.getBody();
            if (requestBody != null && req instanceof HttpEntityEnclosingRequestBase) {
                try {
                    HttpEntityEnclosingRequestBase op = (HttpEntityEnclosingRequestBase) req;
                    op.setEntity(new StringEntity(requestBody));
                } catch (UnsupportedEncodingException e) {
                    platform.notifyFailure(callback, e);
                }
            }
            for (Map.Entry<String, String> header : request.getHeaders()) {
                req.setHeader(header.getKey(), header.getValue());
            }
            int statusCode = -1;
            String statusLineMessage = null;
            Map<String, String> responseHeaders = new HashMap<String, String>();
            String responseBody = null;
            try {
                org.apache.http.HttpResponse response = httpclient.execute(req);
                StatusLine statusLine = response.getStatusLine();
                statusCode = statusLine.getStatusCode();
                statusLineMessage = statusLine.getReasonPhrase();
                for (Header header : response.getAllHeaders()) {
                    responseHeaders.put(header.getName(), header.getValue());
                }
                responseBody = EntityUtils.toString(response.getEntity());
                HttpResponse httpResponse = new HttpResponse(statusCode, statusLineMessage, responseHeaders,
                        responseBody);
                platform.notifySuccess(callback, httpResponse);
            } catch (Throwable cause) {
                HttpErrorType errorType = cause instanceof ConnectTimeoutException
                        || cause instanceof HttpHostConnectException
                        || cause instanceof ConnectionPoolTimeoutException
                        || cause instanceof UnknownHostException ? HttpErrorType.NETWORK_FAILURE
                                : HttpErrorType.SERVER_ERROR;
                HttpException reason = new HttpException(statusCode, statusLineMessage, responseBody, cause,
                        errorType);
                platform.notifyFailure(callback, reason);
            }
        }
    });
}

From source file:com.makotosan.vimeodroid.ApplicationEx.java

private HttpClient createHttpClient() {
    // Log.d(TAG, "createHttpClient()...");

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);
    HttpProtocolParams.setUserAgent(params, "Vimeo Droid");

    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
    return new DefaultHttpClient(conMgr, params);

}

From source file:com.vinaysshenoy.easyoauth.http.HttpManager.java

private void initHttpClient() {

    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setUserAgent(params, mHttpConfig.userAgent);
    HttpProtocolParams.setVersion(params, mHttpConfig.httpVersion);
    HttpProtocolParams.setContentCharset(params, mHttpConfig.contentCharset);

    HttpConnectionParams.setStaleCheckingEnabled(params, mHttpConfig.enableStaleChecking);
    HttpConnectionParams.setConnectionTimeout(params, mHttpConfig.connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, mHttpConfig.socketTimeout);
    HttpConnectionParams.setSocketBufferSize(params, mHttpConfig.socketBufferSize);

    HttpClientParams.setRedirecting(params, mHttpConfig.isRedirecting);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(//from w w  w  .  j  a va  2  s  . co m
            new Scheme(HttpConfig.KEY_HTTP, PlainSocketFactory.getSocketFactory(), mHttpConfig.httpPort));
    schemeRegistry.register(
            new Scheme(HttpConfig.KEY_HTTPS, SSLSocketFactory.getSocketFactory(), mHttpConfig.httpsPort));

    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
    mHttpClient = new DefaultHttpClient(manager, params);
}

From source file:com.doculibre.constellio.utils.ConnectorManagerRequestUtils.java

public static Element sendGet(ConnectorManager connectorManager, String servletPath,
        Map<String, String> paramsMap) {
    if (paramsMap == null) {
        paramsMap = new HashMap<String, String>();
    }//w  ww  .  j  av a2  s .co m

    try {
        HttpParams params = new BasicHttpParams();
        for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
            String paramName = (String) it.next();
            String paramValue = (String) paramsMap.get(paramName);
            params.setParameter(paramName, paramValue);
        }

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);
        URL connectorManagerURL = new URL(connectorManager.getUrl());
        HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort());

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        try {
            String target = connectorManager.getUrl() + servletPath;
            boolean firstParam = true;
            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
                String paramName = (String) it.next();
                String paramValue = (String) paramsMap.get(paramName);

                if (firstParam) {
                    target += "?";
                    firstParam = false;
                } else {
                    target += "&";
                }
                target += paramName + "=" + paramValue;
            }

            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", target);
            LOGGER.fine(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.fine("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.fine(entityText);
            LOGGER.fine("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.fine("Connection kept alive...");
            }

            try {
                Document xml = DocumentHelper.parseText(entityText);
                return xml.getRootElement();
            } catch (Exception e) {
                LOGGER.severe("Error caused by text : " + entityText);
                throw e;
            }
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.leanengine.RestService.java

private HttpClient getClient() {
    if (client == null) {
        synchronized (this) {
            if (client == null) {
                if (configuration != null) {
                    final HttpParams params = new BasicHttpParams();
                    HttpConnectionParams.setConnectionTimeout(params, configuration.getConnectionTimeout());
                    HttpProtocolParams.setVersion(params, configuration.getHttpVersion());
                    HttpProtocolParams.setContentCharset(params, configuration.getContentCharset());

                    final SchemeRegistry schemeRegistry = new SchemeRegistry();
                    schemeRegistry.register(
                            new Scheme("http", configuration.getPlainFactory(), configuration.getPort()));
                    schemeRegistry.register(
                            new Scheme("https", configuration.getSslFactory(), configuration.getSslPort()));

                    final ClientConnectionManager ccm = configuration.createClientConnectionManager(params,
                            schemeRegistry);

                    client = configuration.createClient(ccm, params);
                } else {
                    client = new DefaultHttpClient();
                }//from   w w w . ja  va 2  s  .  com
            }
        }
    }
    return client;
}

From source file:com.jsquant.listener.JsquantContextListener.java

public void contextInitialized(ServletContextEvent sce) {
    contextDestroyed(sce);//from  ww  w  . ja v a  2 s.co  m
    ServletContext context = sce.getServletContext();

    String fileCachePath = getFileCachePath(context);
    context.setAttribute(ATTR_FILE_CACHE, new FileCache(fileCachePath));

    HttpParams params = new BasicHttpParams();
    //params.setParameter("http.useragent", "Mozilla/5.0");
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    final SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    final ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
    final HttpClient httpClient = new DefaultHttpClient(manager, params);
    //HttpHost proxy = new HttpHost("someproxy.com", 80);
    //httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    context.setAttribute(ATTR_HTTP_CLIENT, httpClient);
}

From source file:com.imaginary.home.cloud.api.call.LocationCall.java

static public void main(String... args) throws Exception {
    if (args.length < 1) {
        System.err.println("You must specify an action");
        System.exit(-1);// w  w  w  .j av a2s  .  co m
        return;
    }
    String action = args[0];

    if (action.equalsIgnoreCase("initializePairing")) {
        if (args.length < 5) {
            System.err.println("You must specify a location ID");
            System.exit(-2);
            return;
        }
        String endpoint = args[1];
        String locationId = args[2];
        String apiKeyId = args[3];
        String apiKeySecret = args[4];

        HashMap<String, Object> act = new HashMap<String, Object>();

        act.put("action", "initializePairing");

        HttpParams params = new BasicHttpParams();

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

        HttpClient client = new DefaultHttpClient(params);

        HttpPut method = new HttpPut(endpoint + "/location/" + locationId);
        long timestamp = System.currentTimeMillis();

        method.addHeader("Content-Type", "application/json");
        method.addHeader("x-imaginary-version", CloudService.VERSION);
        method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));
        method.addHeader("x-imaginary-api-key", apiKeyId);
        method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"),
                "put:/location/" + locationId + ":" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION));

        //noinspection deprecation
        method.setEntity(new StringEntity((new JSONObject(act)).toString(), "application/json", "UTF-8"));

        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommunicationException(e);
        }
        if (status.getStatusCode() == HttpServletResponse.SC_OK) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject u = new JSONObject(json);

            System.out.println((u.has("pairingCode") && !u.isNull("pairingCode")) ? u.getString("pairingCode")
                    : "--no code--");
        } else {
            System.err.println("Failed to initialize pairing  (" + status.getStatusCode() + ": "
                    + EntityUtils.toString(response.getEntity()));
            System.exit(status.getStatusCode());
        }
    } else if (action.equalsIgnoreCase("create")) {
        if (args.length < 7) {
            System.err.println("create ENDPOINT NAME DESCRIPTION TIMEZONE API_KEY_ID API_KEY_SECRET");
            System.exit(-2);
            return;
        }
        String endpoint = args[1];
        String name = args[2];
        String description = args[3];
        String tz = args[4];
        String apiKeyId = args[5];
        String apiKeySecret = args[6];

        HashMap<String, Object> lstate = new HashMap<String, Object>();

        lstate.put("name", name);
        lstate.put("description", description);
        lstate.put("timeZone", tz);

        HttpParams params = new BasicHttpParams();

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

        HttpClient client = new DefaultHttpClient(params);

        HttpPost method = new HttpPost(endpoint + "/location");
        long timestamp = System.currentTimeMillis();

        System.out.println(
                "Signing: " + "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION);
        method.addHeader("Content-Type", "application/json");
        method.addHeader("x-imaginary-version", CloudService.VERSION);
        method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp));
        method.addHeader("x-imaginary-api-key", apiKeyId);
        method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"),
                "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION));

        //noinspection deprecation
        method.setEntity(new StringEntity((new JSONObject(lstate)).toString(), "application/json", "UTF-8"));

        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CommunicationException(e);
        }
        if (status.getStatusCode() == HttpServletResponse.SC_CREATED) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject u = new JSONObject(json);

            System.out.println((u.has("locationId") && !u.isNull("locationId")) ? u.getString("locationId")
                    : "--no location--");
        } else {
            System.err.println("Failed to create location  (" + status.getStatusCode() + ": "
                    + EntityUtils.toString(response.getEntity()));
            System.exit(status.getStatusCode());
        }
    } else {
        System.err.println("No such action: " + action);
        System.exit(-3);
    }
}

From source file:com.gmail.nagamatu.radiko.installer.MySSLSocketFactory.java

public static HttpClient getNewHttpClient() {
    try {/*from w  w w .  jav a  2 s  . co m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.weiboa.data.WeiboOAuthConnect.java

public WeiboOAuthConnect(SharedPreferences sp) {
    super(sp);/*from   w w  w .  j  a v a  2 s . com*/

    // initialize http connection
    HttpParams parameters = new BasicHttpParams();
    HttpProtocolParams.setVersion(parameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(parameters, false);
    HttpConnectionParams.setTcpNoDelay(parameters, true);
    HttpConnectionParams.setSocketBufferSize(parameters, 8192);

    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager tsccm = new ThreadSafeClientConnManager(parameters, schReg);
    mClient = new DefaultHttpClient(tsccm, parameters);

    mConsumer = new CommonsHttpOAuthConsumer(com.weiboa.oauth.OAuthKeys.CONSUMER_KEY,
            com.weiboa.oauth.OAuthKeys.CONSUMER_SECRET);

    loadSavedKeys(sp);
}

From source file:ch.cyberduck.core.http.HTTP4Session.java

/**
 * Create new HTTP client with default configuration and custom trust manager.
 *
 * @return A new instance of a default HTTP client.
 *//*from w w w  .  ja v  a2 s.c  o  m*/
protected AbstractHttpClient http() {
    if (null == http) {
        final HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, getEncoding());
        HttpProtocolParams.setUserAgent(params, getUserAgent());

        AuthParams.setCredentialCharset(params, "ISO-8859-1");

        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoTimeout(params, timeout());
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        HttpClientParams.setRedirecting(params, true);
        HttpClientParams.setAuthenticating(params, true);

        SchemeRegistry registry = new SchemeRegistry();
        // Always register HTTP for possible use with proxy
        registry.register(new Scheme("http", host.getPort(), PlainSocketFactory.getSocketFactory()));
        if ("https".equals(this.getHost().getProtocol().getScheme())) {
            org.apache.http.conn.ssl.SSLSocketFactory factory = new SSLSocketFactory(
                    new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(),
                    org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            registry.register(new Scheme(host.getProtocol().getScheme(), host.getPort(), factory));
        }
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.instance();
            if ("https".equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPSProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)));
                }
            }
            if ("http".equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host)));
                }
            }
        }
        ClientConnectionManager manager = new SingleClientConnManager(registry);
        http = new DefaultHttpClient(manager, params);
        this.configure(http);
    }
    return http;
}