HttpGet/客户端和 HTTPS
以前,我使用 此处 讨论的自定义 TrustManager 来执行此操作
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
MyXMLHandler mHandler = new MyXMLHandler();
xr.setContentHandler(mHandler);
xr.parse(new InputSource(buildUrlString()));
(其中 buildUrlString() 返回一个包含要调用的 https:// url 的字符串),效果很好。但是,我现在希望能够向相同的 url 发送 Accept-Encoding 标头以进行 gzip 压缩。我可以这样做,
HttpUriRequest request = new HttpGet(buildUrlString());
request.addHeader("Accept-Encoding", "gzip");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if ((contentEncoding != null)
&& contentEncoding.getValue().equalsIgnoreCase("gzip"))
{
instream = new GZIPInputStream(instream);
}
xr.parse(new InputSource(instream));
但这会带回我想忽略的“不受信任的服务器证书”错误。我如何让它使用 HTTPS?或者,有更好的方法来做到这一点吗? (我需要先检查一些东西,以确保手机确实可以接受我所说的 gzip 压缩网页吗?)
Previously, I used custom TrustManager talked about here to do this
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
MyXMLHandler mHandler = new MyXMLHandler();
xr.setContentHandler(mHandler);
xr.parse(new InputSource(buildUrlString()));
(where buildUrlString() returns a string containing the https:// url to call) which works fine. However, I want to now be able to send the same url an Accept-Encoding header for gzip compression. I can do that like this
HttpUriRequest request = new HttpGet(buildUrlString());
request.addHeader("Accept-Encoding", "gzip");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if ((contentEncoding != null)
&& contentEncoding.getValue().equalsIgnoreCase("gzip"))
{
instream = new GZIPInputStream(instream);
}
xr.parse(new InputSource(instream));
but that brings back the "Not trusted server certificate" error that I want to ignore. How do I make it do HTTPS? Alternatively, is there a better way to do this? (And is there something I need to check first to make sure the phone really can accept the gzipped webpages that I'm saying it can?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想使用 Apache HTTP 客户端 API,您可以通过扩展 DefaultHttpClient 来继续使用自定义 TrustManager
If you want to use Apache HTTP client API you can keep using your custom TrustManager by extending the DefaultHttpClient
实际上,这是可行的:
不过,我仍然不确定这是最好的解决方案,所以我会暂时保留这个问题,以防有人有更好的想法。 :)
Actually this works:
I'm still not sure this is the best solution, though, so I'll leave the question up for a bit in case anyone has better ideas. :)