【发布时间】:2011-05-13 02:41:33
【问题描述】:
您好,
我正在开发一个 Android 应用,需要通过 https 打开一个 url(带有 POST 参数)并获取响应。
还有一个复杂的问题是我有一个自签名证书。我还需要接受 cookie。
有人对从哪里开始有任何想法吗?
非常感谢,
【问题讨论】:
您好,
我正在开发一个 Android 应用,需要通过 https 打开一个 url(带有 POST 参数)并获取响应。
还有一个复杂的问题是我有一个自签名证书。我还需要接受 cookie。
有人对从哪里开始有任何想法吗?
非常感谢,
【问题讨论】:
我设法让这一切都与 cookie 和未签名的 https 异步工作。
我在这里使用了代码:
http://masl.cis.gvsu.edu/2010/04/05/android-code-sample-asynchronous-http-connections/
并在此处使用 Brian Yager 的代码修改为未签名的 https:
Self-signed SSL acceptance on Android
(将上述代码添加到HttpConnection.java中run()的开头)
为了让 cookie 工作,我不得不修改一些代码(来自 HttpConnection.java 的 POST sn-p):
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;
非常感谢大家为我指明方向,
【讨论】:
Android 附带了 apache commons http 库。 设置 https 发布请求非常简单:
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 使用 commons http 库的 4.x 版本,因为低于 4.0 的所有版本都已超出其生命周期。
我无法确切说明如何将自签名证书注册到 HttpClient,但 mybe the commons http 文档会有所帮助:
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
【讨论】: