Java – How do I perform an https get request through an http client?

How do I perform an https get request through an http client?… here is a solution to the problem.

How do I perform an https get request through an http client?

I’m trying to make a GET request over the https endpoint and I’m not sure if any special handling is required, but here’s my code:

String foursquareURL = "https://api.foursquare.com/v2/venues/search?ll=" + latitude + "," + longitude + "&client_id="+CLIENT_ID+"&client_secret="+CLIENT_ SECRET;
            System.out.println("Foursquare URL is " + foursquareURL);

try {
                Log.v("HttpClient", "Preparing to create a request " + foursquareURL);
                URI foursquareURI = new URI(foursquareURL);
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(new HttpGet(foursquareURI));
                content = response.getEntity().getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(content));
                String strLine;
                String result = "";
                while ((strLine = br.readLine()) != null)   {
                      result += strLine;
                }

editTextShowLocation.setText(result);
                Log.v("result of the parser is", result);

} catch (Exception e) {
                  Log.v("Exception", e.getLocalizedMessage());
              }

Solution

I’m not sure if this approach works for Android, but we’re seeing the same issue in server-side Java using HttpClient and HTTPS URLs. Here’s how we solve the problem:

First, we copy/adapt the implementation of the EasySSLProtocolSocketFactory class into our own codebase. You can find the source code here:

http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/contrib/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java?view=markup

With this class, we can create a new HttpClient instance:

HttpClient httpClient = new HttpClient();
mHttpClient = httpClient;
Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", easyhttps);

The use of EasySSLProtocolSocketsfactory will allow your HttpClient to ignore any certificate failures/issues when making requests.

Related Problems and Solutions