0
votes

I've an android app that send an http request to a server, and receive a response from it. Until today, i send request to server in this way:

 DefaultHttpClient httpClient = new DefaultHttpClient();
 HttpPost httpPost = new HttpPost(http_url);
 httpPost.setEntity(new UrlEncodedFormEntity(params));

 HttpResponse httpResponse = httpClient.execute(httpPost);
 HttpEntity httpEntity = httpResponse.getEntity();
 InputStream is = httpEntity.getContent();

where http_url contain an http url (http://www.mydomain.it/script.php) for script i need to invoke. Now i've buy and installed an SSL certificate on my server, so i need to start to use it for crypt data.

I've used the same code for send and receive data, but instead of http_url i've used https_url (https://www.mydomain.it/script.php). With wireshark i've noticed that packet is encrypted, but i would know if this is the correct way to send an https request. Does DefaultHttpClient provide to all operations for start crypted communication, or there's other Java class for do that?

1

1 Answers

0
votes

Use this method for https request to get httpClient:

public DefaultHttpClient getNewHttpClient() {
    try {
        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("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

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