Java – HttpGet/client and HTTPS

HttpGet/client and HTTPS… here is a solution to the problem.

HttpGet/client and HTTPS

Previously, I used a custom TrustManager to say here to do this

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();

XMLReader xr = sp.getXMLReader();
MyXMLHandler mHandler = new MyXMLHandler();
xr.setContentHandler(mHandler);

xr.parse(new InputSource(buildUrlString()));

(where buildUrlString() returns a string containing the https://url to be called) works fine. However, I now want to be able to send an Accept-Encoding header to the same url for gzip compression. I can do this

HttpUriRequest request = new HttpGet(buildUrlString());
request.addHeader("Accept-Encoding", "gzip");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);

InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if ((contentEncoding != null)
    && contentEncoding.getValue().equalsIgnoreCase("gzip")) 
{ 
  instream = new GZIPInputStream(instream);
} 
xr.parse(new InputSource(instream));

But this brings back the “untrusted server certificate” error that I want to ignore. How do I get it to do HTTPS? Or, is there a better way to do this? (Is there anything I need to check first to make sure the phone really accepts the gzip page I said is acceptable?) )

Solution

If you want to use the Apache HTTP Client API, you can continue to use a custom TrustManager by extending the DefaultHttpClient

import org.apache.http.conn.ssl.SSLSocketFactory;

public class MyHttpClient extends DefaultHttpClient {
  final Context context;

public MyHttpClient(Context context) {
    this.context = context;
  }

@Override 
  protected ClientConnectionManager createClientConnectionManager() {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", newSslSocketFactory(), 443));
    return new SingleClientConnManager(getParams(), registry);
  }

private SSLSocketFactory newSslSocketFactory() {
    try {
      TrustManager tm = new MyCustomTrustManager();
      SSLContext ctx = SSLContext.getInstance("TLS");
      ctx.init(null, new TrustManager[] {tm}, null);
      SSLSocketFactory sf = new SSLSocketFactory(ctx);
      return new SSLSocketFactory(ctx);
    } catch (Exception e) {
      throw new Error(e);
    }
  }
}

Related Problems and Solutions