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:com.softcoil.ApnDefaults.java

/**
 * This method provides a means for clients to report new, good APN connection parameters
 * to a central repository so that they can be integrated with this class and shared with
 * the public.//from w w w .  j  av a 2  s.c o  m
 *
 * It contains protections so that new ApnParameters are only reported to the server the first
 * time this method is called. In addition, it uses a short connection timeout so it can be
 * safely called from your current worker thread without worry that it will unnecessarily
 * delay your process.
 *
 * It should be called immediately after successfully sending a MMS message. Example:<br/>
 *  <pre>
 *  //Send your MMS using whatever method you currently use.
 *  byte[] response = myMmsHttpPost(mmscUrl, mmsProxy, mmsProxyPort, sendReqPdu);
 *
 *  //Parse the response.
 *  SendConf sendConf = (SendConf) new PduParser(response).parse();
 *
 *  //Check to see if the response was success.
 *  if(sendConf != null && sendConf.getResponseStatus() == PduHeaders.RESPONSE_STATUS_OK) {
 *      //Report the ApnParameters used for the post.
 *      ApnParameters parameters = new ApnParameters(mmscUrl, mmsProxy, mmsProxyPort);
 *      ApnDefaults.reportApnData(context, parameters);
 *  }
 *
 *  //Continue your process.
 *  ...
 *  </pre>
 *
 *  In order for this class to be useful we must collect data from as many working
 *  configurations as possible. Adding a call to this method after a successful MMSC operation
 *  in your app will help us all to provide a good MMS experience to our users.
 *
 * @param context The current context.
 * @param apnParameters The known good ApnParameters to report.
 */
public static void reportApnData(Context context, ApnParameters apnParameters) {

    if (apnParameters == null)
        return;

    String apnData = apnParameters.getMmscUrl() + "|" + apnParameters.getProxyAddress() + "|"
            + apnParameters.getProxyPort();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String previousApnData = prefs.getString(PREF_KEY_LAST_APN_REPORT, null);

    if (!apnData.equals(previousApnData)) {

        //Save new apn data
        prefs.edit().putString(PREF_KEY_LAST_APN_REPORT, apnData).apply();

        //Report new apn data
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String networkOperator = tm.getNetworkOperator();
        String networkOperatorName = tm.getNetworkOperatorName();
        String simOperator = tm.getSimOperator();
        String simOperatorName = tm.getSimOperatorName();

        //Create HttpClient
        AndroidHttpClient client = AndroidHttpClient.newInstance("ApnDefaults/0.1");
        HttpParams params = client.getParams();
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpConnectionParams.setConnectionTimeout(params, 1 * 1000); //Set timeout to wait for a connection.
        HttpConnectionParams.setSoTimeout(params, 1 * 1000); //Set timeout to wait for a response.
        try {
            StringBuffer uriString = new StringBuffer(REPORT_URL).append("?")
                    //Report the MMSC connection used.
                    .append("apnData=").append(URLEncoder.encode(apnData, "UTF-8"))
                    //SIM and Network data are reported to enable determining which
                    //parameters work under which circumstances.
                    .append("&simOperator=").append(URLEncoder.encode(simOperator, "UTF-8"))
                    .append("&simOperatorName=").append(URLEncoder.encode(simOperatorName, "UTF-8"))
                    .append("&simCountry=").append(URLEncoder.encode(tm.getSimCountryIso(), "UTF-8"))
                    .append("&networkOperator=").append(URLEncoder.encode(networkOperator, "UTF-8"))
                    .append("&networkOperatorName=").append(URLEncoder.encode(networkOperatorName, "UTF-8"))
                    .append("&networkCountry=").append(URLEncoder.encode(tm.getNetworkCountryIso(), "UTF-8"));

            URI uri = new URI(uriString.toString());

            //Send request
            client.execute(new HttpGet(uri));
            client.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.cloudifysource.restclient.RestClient.java

/**
 * Returns a HTTP client configured to use SSL.
 * /*ww w  .  ja va 2  s  .co  m*/
 * @param url
 * 
 * @return HTTP client configured to use SSL
 * @throws org.cloudifysource.restclient.exceptions.RestClientException
 *             Reporting different failures while creating the HTTP client
 */
private DefaultHttpClient getSSLHttpClient(final URL url) throws RestClientException {
    try {
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        // TODO : support self-signed certs if configured by user upon "connect"
        trustStore.load(null, null);

        final SSLSocketFactory sf = new RestSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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

        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme(HTTPS, sf, url.getPort()));

        final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (final Exception e) {
        throw new RestClientException(FAILED_CREATING_CLIENT, "Failed creating http client",
                ExceptionUtils.getFullStackTrace(e));
    }
}

From source file:org.craftercms.profile.impl.ProfileRestClientService.java

/**
 * @param httpParams/*from ww  w .  j  a  va 2s  .  c om*/
 */
private void setHttpProtocolParams(HttpParams httpParams) {
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "utf-8");
}

From source file:org.dasein.cloud.aws.AWSCloud.java

public @Nonnull HttpClient getClient(boolean multipart) throws InternalException {
    ProviderContext ctx = getContext();/*from  ww w .j a  va2  s.c om*/
    if (ctx == null) {
        throw new InternalException("No context was specified for this request");
    }

    final HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    if (!multipart) {
        HttpProtocolParams.setContentCharset(params, Consts.UTF_8.toString());
    }
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");

    Properties p = ctx.getCustomProperties();
    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPortStr = p.getProperty("proxyPort");
        int proxyPort = 0;
        if (proxyPortStr != null) {
            proxyPort = Integer.parseInt(proxyPortStr);
        }
        if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
        }
    }
    DefaultHttpClient httpClient = new DefaultHttpClient(params);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
            request.setParams(params);
        }
    });
    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header header = entity.getContentEncoding();
                if (header != null) {
                    for (HeaderElement codec : header.getElements()) {
                        if (codec.getName().equalsIgnoreCase("gzip")) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            break;
                        }
                    }
                }
            }
        }
    });
    return httpClient;
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

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

    if (ctx == null) {
        throw new AzureConfigException("No context was defined for this request");
    }//from w w  w .ja  v a 2  s.c  o  m
    String endpoint = getStorageEnpoint();
    boolean ssl = endpoint.startsWith("https");
    int targetPort;

    try {

        URI uri = new URI(endpoint);
        targetPort = uri.getPort();

        if (targetPort < 1) {
            targetPort = (ssl ? 443 : 80);
        }
    } catch (URISyntaxException e) {
        throw new AzureConfigException(e);
    }
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

    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:org.dasein.cloud.openstack.nova.os.AbstractMethod.java

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

    if (ctx == null) {
        throw new InternalException("No context was defined for this request");
    }//from ww  w  .  j  a v a2 s  .  c  o  m
    String endpoint = ctx.getCloud().getEndpoint();

    if (endpoint == null) {
        throw new InternalException("No cloud endpoint was defined");
    }
    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, "");

    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"));
        }
    }
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (provider.isInsecure()) {
        try {
            client.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {

                        public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                                throws CertificateException {
                            return true;
                        }
                    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    return client;
}

From source file:org.dasein.cloud.virtustream.VirtustreamMethod.java

private @Nonnull HttpClient getClient(URI uri) throws InternalException, CloudException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new InternalException();
    }//  w  ww  .jav a 2s .  co  m
    boolean ssl = uri.getScheme().startsWith("https");
    HttpParams params = new BasicHttpParams();

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

    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:org.klnusbaum.udj.network.ServerConnection.java

public static DefaultHttpClient getHttpClient() throws IOException {
    if (httpClient == null) {
        SchemeRegistry schemeReg = new SchemeRegistry();
        schemeReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), SERVER_PORT));
        BasicHttpParams params = new BasicHttpParams();
        ConnManagerParams.setMaxTotalConnections(params, 100);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUseExpectContinue(params, true);

        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeReg);
        httpClient = new DefaultHttpClient(cm, params);
    }/*from ww  w.  j  a v a 2s.  c om*/
    return httpClient;
}

From source file:org.whitesource.agent.client.WssServiceClientImpl.java

/**
 * Constructor//from  www .  j av a  2 s .c  o  m
 *
 * @param serviceUrl WhiteSource service URL to use.
 * @param setProxy WhiteSource set proxy, whether the proxy settings is defined or not.
 * @param connectionTimeoutMinutes WhiteSource connection timeout, whether the connection timeout is defined or not (default to 60 minutes).
 */
public WssServiceClientImpl(String serviceUrl, boolean setProxy, int connectionTimeoutMinutes,
        boolean ignoreCertificateCheck) {
    gson = new Gson();

    if (serviceUrl == null || serviceUrl.length() == 0) {
        this.serviceUrl = ClientConstants.DEFAULT_SERVICE_URL;
    } else {
        this.serviceUrl = serviceUrl;
    }

    if (connectionTimeoutMinutes <= 0) {
        this.connectionTimeout = ClientConstants.DEFAULT_CONNECTION_TIMEOUT_MINUTES * TO_MILLISECONDS;
    } else {
        this.connectionTimeout = connectionTimeoutMinutes * TO_MILLISECONDS;
    }

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, this.connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, this.connectionTimeout);
    HttpClientParams.setRedirecting(params, true);

    httpClient = new DefaultHttpClient();

    if (ignoreCertificateCheck) {
        try {
            logger.warn("Security Warning - Trusting all certificates");

            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            char[] password = SOME_PASSWORD.toCharArray();
            keystore.load(null, password);

            WssSSLSocketFactory sf = new WssSSLSocketFactory(keystore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            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);

            httpClient = new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    if (setProxy) {
        findDefaultProxy();
    }
}