【问题标题】:Android: Get response from a https urlAndroid:从 https url 获取响应
【发布时间】:2011-05-13 02:41:33
【问题描述】:

您好,

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

还有一个复杂的问题是我有一个自签名证书。我还需要接受 cookie。

有人对从哪里开始有任何想法吗?

非常感谢,

【问题讨论】:

    标签: android post https


    【解决方案1】:

    我设法让这一切都与 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;
    

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

    【讨论】:

      【解决方案2】:

      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

      【讨论】:

      • 您好,非常感谢您的回复。它工作得很好。但是无法使未签名的证书正常工作。另外,关于如何让您的代码异步工作的任何想法?我不希望 UI 在等待响应时挂起。
      • 正如大卫所说,您必须启动一个新线程并将http post操作放入run方法中。可以使用 Android 处理程序系统在线程之间交换数据。您可能想查看 Android 基础页面:developer.android.com/guide/topics/fundamentals.html#threads
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多