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 开发者_StackOverflow社区need to accept cookies.
Anyone have any ideas about where to get started?
Many thanks in advance,
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
I managed to get it all working asyncronously with both cookies and unsigned https.
I used the code here:
http://masl.cis.gvsu.edu/2010/04/05/android-code-sample-asynchronous-http-connections/
and modified for unsigned https using Brian Yarger's code here:
Self-signed SSL acceptance on Android
(Add the above code to the beginning of run() in HttpConnection.java)
To get the cookies to work, I had to modify some code (POST snippet from HttpConnection.java):
case POST:
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(data));
httpPost.addHeader("Cookie", Cookie.getCookie());
response = httpClient.execute(httpPost);
Header[] headers=response.getAllHeaders();
for(int i=0;i<headers.length;i++){
if(headers[i].getName().equalsIgnoreCase("Set-Cookie")){
//Log.i("i",headers[i].getName()+"---"+headers[i].getValue());
Cookie.setCookie(headers[i].getValue());
break;
}
}
break;
Many thanks to everyone for pointing me in the direction,
精彩评论