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:cn.com.loopj.android.http.MySSLSocketFactory.java

/**
 * Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore
 *
 * @param keyStore custom provided KeyStore instance
 * @return DefaultHttpClient// w w  w  .  j a v a 2  s.  co  m
 */
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {

    try {
        SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

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

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

public static Element sendPost(ConnectorManager connectorManager, String servletPath, Document document) {
    try {//  w  w w  .j a  v  a2s  .c  o m
        HttpParams params = new BasicHttpParams();
        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 {
            HttpEntity requestBody;
            if (document != null) {
                //                 OutputFormat format = OutputFormat.createPrettyPrint();
                OutputFormat format = OutputFormat.createCompactFormat();
                StringWriter stringWriter = new StringWriter();
                XMLWriter xmlWriter = new XMLWriter(stringWriter, format);
                xmlWriter.write(document);
                String xmlAsString = stringWriter.toString();
                requestBody = new StringEntity(xmlAsString, "UTF-8");
            } else {
                requestBody = null;
            }
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }

            String target = connectorManager.getUrl() + servletPath;

            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", target);
            request.setEntity(requestBody);
            LOGGER.info(">> 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.info("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.info(entityText);
            LOGGER.info("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.info("Connection kept alive...");
            }

            Document xml = DocumentHelper.parseText(entityText);
            return xml.getRootElement();
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.baidu.qa.service.test.client.SoapReqImpl.java

private static String sendSoap(String hosturl, String ip, int port, String action, String method, String xml,
        boolean isHttps) throws Exception {
    if (isHttps) {
        return sendSoapViaHttps(hosturl, ip, port, action, method, xml);
    }/*from   ww  w.  j  ava 2  s. c om*/

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");// must be UTF-8
    HttpProtocolParams.setUserAgent(params, "itest-by-HttpCore/4.2");

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    // log.info("ip:port - " + ip + ":" + port );
    HttpHost host = new HttpHost(ip, port);// TODO

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    conn.setSocketTimeout(10000);
    HttpConnectionParams.setSoTimeout(params, 10000);
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

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

    String res = null;

    try {
        // HttpEntity requestBody = new
        // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO
        byte[] b = xml.getBytes("UTF-8"); // must be UTF-8
        InputStream is = new ByteArrayInputStream(b, 0, b.length);

        HttpEntity requestBody = new InputStreamEntity(is, b.length,
                ContentType.create("text/xml;charset=UTF-8"));// must be
        // UTF-8

        // .create("application/xop+xml; charset=UTF-8; type=\"text/xml\""));//
        // TODO

        // RequestEntity re = new InputStreamRequestEntity(is, b.length,
        // "application/xop+xml; charset=UTF-8; type=\"text/xml\"");
        // postmethod.setRequestEntity(re);

        if (!conn.isOpen()) {
            Socket socket = new Socket(host.getHostName(), host.getPort());
            conn.bind(socket, params);
        }
        BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", action);

        // add the 3 headers below
        request.addHeader("Accept-Encoding", "gzip,deflate");
        request.addHeader("SOAPAction", hosturl + action + method);// SOAP action
        request.addHeader("uuid", "itest");// for editor token of DR-Api

        request.setEntity(requestBody);
        log.info(">> 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);

        log.info("<< Response: " + response.getStatusLine());

        String contentEncoding = null;
        Header ce = response.getEntity().getContentEncoding();
        if (ce != null) {
            contentEncoding = ce.getValue();
        }

        if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
            GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent());
            Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            while (in.hasNextLine()) {
                sb.append(in.nextLine()).append(System.getProperty("line.separator"));
            }
            res = sb.toString();
        } else {
            res = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        log.info(res);

        log.info("==============");
        if (!connStrategy.keepAlive(response, context)) {
            conn.close();
        } else {
            log.info("Connection kept alive...");
        }
    } finally {
        try {
            conn.close();
        } catch (IOException e) {
        }
    }
    return res;
}

From source file:org.wso2.bam.integration.tests.reciever.RESTAPITestCase.java

@BeforeClass(groups = { "wso2.bam" })
private static void init() {

    DATA_RECEIVER = "/datareceiver/1.0.0";

    //        host = FrameworkSettings.HOST_NAME;
    //        httpsPort = Integer.parseInt(FrameworkSettings.HTTPS_PORT);

    restAppParentURL = "https://" + host + ":" + httpsPort + DATA_RECEIVER;
    streamsURL = restAppParentURL + "/streams";

    streamURL = restAppParentURL + "/stream";
    stockQuoteVersion1URL = streamURL + "/stockquote.stream/1.0.2/";

    stockQuoteVersion2URL = streamURL + "/stockquote.stream.2/2.0.0";

    stockQuoteVersion3URL = streamURL + "/labit.stream/0.0.3";
    stockQuoteVersion4URL = streamURL + "/eu.ima.event.stream/1.2.0";
    stockQuoteVersion5URL = streamURL + "/eu.ima.event.stream.2/1.3.0";

    try {/*from   w w  w  .  ja  v a 2s. c o m*/
        events1 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events1.json"));
        events2 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events2.json"));
        events3 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events3.json"));
        events4 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events4.json"));
        events5 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events5.json"));

        streamdefn1 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn1.json"));
        streamdefn2 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn2.json"));
        streamdefn3 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn3.json"));
        streamdefn4 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn4.json"));
        streamdefn5 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn5.json"));

        TrustManager easyTrustManager = new X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", sf, httpsPort);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "utf-8");
        params.setBooleanParameter("http.protocol.expect-continue", false);

        client = new DefaultHttpClient(params);
        client.getConnectionManager().getSchemeRegistry().register(httpsScheme);

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}

From source file:com.lgallardo.qbittorrentclient.JSONParser.java

public JSONObject getJSONFromUrl(String url) throws JSONParserStatusCodeException {

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }/*w w w.ja  v a 2 s  .  c o  m*/

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient(httpParameters);
    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        // set http parameters

        url = protocol + "://" + hostname + ":" + port + "/" + url;

        //            Log.d("Debug", "url:" + url);

        HttpGet httpget = new HttpGet(url);

        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

        // Build JSON
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();

        // try parse the string to a JSON object
        jObj = new JSONObject(json);

    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    } catch (UnsupportedEncodingException e) {
        Log.e("JSON", "UnsupportedEncodingException: " + e.toString());

    } catch (ClientProtocolException e) {
        Log.e("JSON", "ClientProtocolException: " + e.toString());
        e.printStackTrace();
    } catch (SSLPeerUnverifiedException e) {
        Log.e("JSON", "SSLPeerUnverifiedException: " + e.toString());
        throw new JSONParserStatusCodeException(NO_PEER_CERTIFICATE);
    } catch (IOException e) {
        Log.e("JSON", "IOException: " + e.toString());
        // e.printStackTrace();
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("JSON", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    // return JSON String
    return jObj;
}

From source file:matroskastudycoder.HttpControl.java

public void init(String aHost, String aPort) throws Exception {
    params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    httpexecutor = new HttpRequestExecutor();

    context = new BasicHttpContext(null);
    host = new HttpHost(aHost, Integer.parseInt(aPort));

    connStrategy = new DefaultConnectionReuseStrategy();

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

    //Clear the playlist
    sendGetRequest("/requests/status.xml?command=pl_empty");

    //Load the media
    String m = this.mediaPath;
    m = m.replaceAll("\\\\", "\\\\\\\\");

    sendGetRequest("/requests/status.xml?command=in_play&input=" + URLEncoder.encode(m, "UTF-8"));
    sendGetRequest("/requests/status.xml?command=pl_pause");
    initialized = true;/*from w  ww  .  ja v a2 s  . co m*/
}

From source file:com.webwoz.wizard.server.components.MTinGoogle.java

public void initializeConnection(String proxyHostName, int proxyHostPort) {
    SchemeRegistry supportedSchemes = new SchemeRegistry();
    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, supportedSchemes);

    httpClient = new DefaultHttpClient(ccm, params);

    HttpHost proxyHost = new HttpHost(proxyHostName, proxyHostPort);

    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
}

From source file:pl.xsolve.verfluchter.rest.RestClient.java

private RestResponse executeRequest(HttpUriRequest request) throws IOException {
    Log.v(TAG, "Final request preperations...");

    HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    httpParams.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
    httpParams.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, Charsets.UTF_8.name());

    context = new BasicHttpContext();

    //        if (basicAuthCredentials != null) {
    // ignore that the ssl cert is self signed
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, AuthScope.ANY_PORT), // null here means "any host is OK"
            new UsernamePasswordCredentials(basicAuthCredentials.first, basicAuthCredentials.second));
    clientConnectionManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    context.setAttribute("http.auth.credentials-provider", credentialsProvider);
    //        }/* w  w w.  j ava2  s.c om*/

    //connection (client has to be created for every new connection)
    httpclient = new DefaultHttpClient(clientConnectionManager, httpParams);

    for (Cookie cookie : cookies) {
        Log.v(TAG, "Using cookie " + cookie.getName() + "=" + cookie.getValue() + "...");
        httpclient.getCookieStore().addCookie(cookie);
    }

    try {
        httpResponse = httpclient.execute(request, context);

        int responseCode = httpResponse.getStatusLine().getStatusCode();
        Header[] headers = httpResponse.getAllHeaders();
        String errorMessage = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        Log.v(TAG, "Got cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            Log.v(TAG, "None");
        } else {
            for (Cookie cookie : cookies) {
                Log.v(TAG, "---- " + cookie.toString());
            }
        }

        String message = null;
        InputStream inStream = entity.getContent();
        message = SoulTools.convertStreamToString(inStream);

        // Closing the input stream will trigger connection release
        entity.consumeContent();
        inStream.close();

        return new RestResponse(responseCode, message, headers, cookies, errorMessage);
    } catch (ClientProtocolException e) {
        Log.v(TAG, "Encountered ClientProtocolException!");
        e.printStackTrace();
    } catch (IOException e) {
        Log.v(TAG, "Encountered IOException!");
        e.printStackTrace();
    } finally {
        //always shutdown the connection manager
        httpclient.getConnectionManager().shutdown();
    }

    Log.v(TAG, "Returning null RestResponse!");
    return null;
}

From source file:org.graphity.core.util.jena.DatasetGraphAccessorHTTP.java

static private HttpParams createHttpParams() {
    HttpParams httpParams$ = new BasicHttpParams();
    // See DefaultHttpClient.createHttpParams
    HttpProtocolParams.setVersion(httpParams$, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams$, WebContent.charsetUTF8);
    HttpProtocolParams.setUseExpectContinue(httpParams$, true);
    HttpConnectionParams.setTcpNoDelay(httpParams$, true);
    HttpConnectionParams.setSocketBufferSize(httpParams$, 32 * 1024);
    HttpProtocolParams.setUserAgent(httpParams$, Jena.NAME + "/" + Jena.VERSION);
    return httpParams$;
}

From source file:app.android.auto.net.sampleapp.oauth.blackwork.EasyHttpClient.java

/**
 * Function that creates a ClientConnectionManager which can handle http and https.
 * In case of https self signed or invalid certificates will be accepted.
 *//*from   w  w w.j  av a2s  .c o m*/
@Override
protected ClientConnectionManager createClientConnectionManager() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), HTTP_PORT));
    registry.register(new Scheme("https", new EasySSLSocketFactory(), HTTPS_PORT));
    ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);

    return manager;
}