Android:从https网址获取回复

Eam*_*orr 8 https post android

问候,

我正在开发一个Android应用程序,需要通过https打开一个url(带有POST参数)并获得响应.

我有一个自签名证书的复杂性增加了.我还需要接受cookies.

任何人都有关于从哪里开始的任何想法?

提前谢谢了,

小智 17

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);
Run Code Online (Sandbox Code Playgroud)

Android使用commons http库的4.x版本,因为4.0以下的所有版本都在其生命周期之外.

我无法确切地告诉如何将自签名证书注册到HttpClient,但mybe the commons http文档有助于:

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


Eam*_*orr 3

我设法使用 cookie 和未签名的 https 使其全部异步工作。

我在这里使用了代码:

http://masl.cis.gvsu.edu/2010/04/05/android-code-sample-asynchronous-http-connections/

并使用 Brian Yarger 的代码对未签名的 https 进行了修改:

Android 上的自签名 SSL 接受

(将以上代码添加到HttpConnection.java中run()的开头)

为了让 cookies 工作,我必须修改一些代码(来自 HttpConnection.java 的 POST 片段):

         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;
Run Code Online (Sandbox Code Playgroud)

非常感谢大家给我指明了方向,