Search code examples
androidhttpsandroid-2.3-gingerbread

How do I use the command: HttpEntity?


I wish to settle my long term problem by this question and hope you guys would help, but firstly; I have been having issues to connect to a HTTPS self-signed certificate server for almost 3 weeks. Despite the multiple solutions here, I cannot seem to resolve my problem. Probably I did not know how to use it properly or did not have some files or imported the correct libraries.

I came across some websites that requires me to download a certificate from the https site that I am trying to connect into, and when I did that. I have to do the some steps before I can use the certificate or keystore that I created. I got this solution from this website:

Android: Trusting SSL certificates

// Instantiate the custom HttpClient
DefaultHttpClient client = new MyHttpClient(getApplicationContext());
HttpGet get = new HttpGet("https://www.mydomain.ch/rest/contacts/23");
// Execute the GET call and obtain the response
HttpResponse getResponse = client.execute(get);
HttpEntity responseEntity = getResponse.getEntity();

I have a problem, after the last line, as stated above. What do I do with the responseEntity? How do I use it if I wish to display the https website on a WebView? Some help and explanation would be nice :)


Solution

  • If you want the content from the HttpEntity the correct way does not include calling HttpEntity#getContent() to retrieve a stream and doing tons of pointless stuff already available in the Android SDK.

    Try this instead.

    // Execute the GET call and obtain the response
    HttpResponse getResponse = client.execute(get);
    HttpEntity responseEntity = getResponse.getEntity();
    
    // Retrieve a String from the response entity
    String content = EntityUtils.toString(responseEntity);
    
    // Now content will contain whatever the server responded with and you
    // can pass it to your WebView using #loadDataWithBaseURL
    

    Consider using WebView#loadDataWithBaseURL when displaying content - it behaves a lot nicer.