Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Get response from a https url

Greetings,

I'm developing an Android app and need to open a url (with POST parameters) over https and get the response.

There's the added complication that I have a self-signed certificate. I also need to accept cookies.

Anyone have any ideas about where to get started?

Many thanks in advance,

like image 487
Eamorr Avatar asked Nov 20 '10 15:11

Eamorr


1 Answers

Android comes with the apache commons http library included. Setting up a https post request is quite easy:

HttpPost post = new HttpPost("https://yourdomain.com/yourskript.xyz");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("postValue1", "my Value"));
nameValuePairs.add(new BasicNameValuePair("postValue2", "2nd Value"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();

String responseText = EntityUtils.toString(entity);

Android uses a version 4.x of the commons http library as all versions below 4.0 are out of their lifecycle.

I can't tell exactly how to register a self-signed certificate to the HttpClient, but mybe the commons http documentation helps:

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506

like image 129
marcus Avatar answered Oct 10 '22 12:10

marcus