I wanted to make my own Https Get/Post request on Android platform. In this blog post I will cover my investigation and the quirks I noticed for eg.
– if you are working over wifi behind a proxy server or 3G.
– or what classes to use.
A standard Http 1.1 requests can be made using Java standard HttpUrlConnection class. There is a separate HttpsUrlConnection class for https connections. But now you will also have to write code if(http) use HttpUrlConnection elseif(https) use HttpsUrlConnection.
However, Android comes with Apache HttpClient library (which builds on Sockets) and
- is much more powerful
- easy to configure different settings,eg, https, http, proxy settings etc.
- Easy to use.
- It has a tutorial to get you going and if in doubt just read the code (its open source)!
Android itself uses this library at various places.
- HttpUrlConnection will work over 3G with external sites. However, when you are connected to wifi it will stop working due to proxy settings. I don’t know at this point how to set the proxy settings.
- HttpClient will work with internal websites without setting proxy and external websites with setting proxy. Remember to use full fqdn always eg. http://www.google.com.
// set proxy
HttpHost proxy = new HttpHost(“myproxy server”, 80);
HttpParams params = new BasicHttpParams();
HttpClient httpClient = new DefaultHttpClient(this.manager, params); // this.manager is an instance of HttpConnectionManager
- Https connections over HttpClient is also very straight forward. A bit reading on Java SSL and SocketFactory is required. And then read the tutorial on HttpClient website. It takes around 1-2 hours to read the material and then its all very easy.
- If you are sending HttpRequest over Https and need to handle with self signed certificates. You will have to create EasySSLSocketFactory and EasyX509TrustManager. Again the tutorial has all the details.
WebView behaves like the browser. All of the below is true for wifi.
- Proxy not set. Both will deny access to external sites. Allows access to the internal sites.
- Proxy set. Both will deny access to internal sites and deny access to external sites.
- When working with browser you will get a warning for the websites which uses self signed certificates.
- When working with Webview you will need to override a function in WebViewClient class
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error)
Unfortunately, the function is not present on Android 2.1. Fortunately, there is an easy workaround which can be followed.