【问题标题】:how to perform an https get request via http client?如何通过 http 客户端执行 https 获取请求?
【发布时间】:2011-11-12 19:11:41
【问题描述】:

我正在尝试通过 https 端点发出 GET 请求,我不确定是否需要任何特殊处理,但以下是我的代码:

String foursquareURL = "https://api.foursquare.com/v2/venues/search?ll=" + latitude + "," + longitude + "&client_id="+CLIENT_ID+"&client_secret="+CLIENT_SECRET;
            System.out.println("Foursquare URL is " + foursquareURL);


try {
                Log.v("HttpClient", "Preparing to create a request " + foursquareURL);
                URI foursquareURI = new URI(foursquareURL);
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(new HttpGet(foursquareURI));
                content = response.getEntity().getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(content));
                String strLine;
                String result = "";
                while ((strLine = br.readLine()) != null)   {
                      result += strLine;
                }

                //editTextShowLocation.setText(result);
                Log.v("result of the parser is", result);

              } catch (Exception e) {
                  Log.v("Exception", e.getLocalizedMessage());
              }

【问题讨论】:

  • 它总是遇到异常,说 api.foursquare.com 并且说地址族不受协议支持
  • 与 HTTPS 没有任何特定关系(因为服务器证书是 Android 的接受者,这是另一回事)。问题是 HTTPS 特有的吗?您是否尝试过在另一个 wibe 网站上使用和不使用 HTTPS 的另一个 URL?
  • hmmm...除了这个带有 https 的 URL 之外,我还没有真正尝试过其他人,我在 2.2.3

标签: java android httpclient


【解决方案1】:

我不确定这种方法是否适用于 Android,但我们在使用带有 HTTPS URL 的 HttpClient 的服务器端 Java 中看到了同样的问题。以下是我们解决问题的方法:

首先,我们将 EasySSLProtocolSocketFactory 类的实现复制/改编到我们自己的代码库中。你可以在这里找到来源:

http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/contrib/org/apache/commons/httpclient/contrib/ssl/EasySSLProtocolSocketFactory.java?view=markup

有了这个类,然后我们创建新的 HttpClient 实例:

HttpClient httpClient = new HttpClient();
mHttpClient = httpClient;
Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", easyhttps);

使用 EasySSLProtocolSocketsfactory 将允许您的 HttpClient 在发出请求时忽略任何证书失败/isses。

【讨论】:

    【解决方案2】:

    看看AndroidHttpClient。它本质上是DefaultHttpClient 的替代方案,它会在您创建它时在后台为您注册一些常用的方案(包括HTTPS)。

    然后您应该能够使用此客户端的实例执行HttpGets,如果您的 URL 指示“https”方案,它将为您处理 SSL。您不必费心注册自己的 SSL 协议/方案等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-13
      • 2018-12-25
      • 1970-01-01
      • 2018-12-06
      • 2012-09-27
      • 2016-02-27
      • 2021-05-07
      • 1970-01-01
      相关资源
      最近更新 更多