java-HttpGet 客户端和HTTPS

java-HttpGet 客户端和HTTPS,第1张

概述以前,我使用自定义TrustManager谈论过here来做到这一点SAXParserFactoryspf=SAXParserFactory.newInstance();SAXParsersp=spf.newSAXParser();XMLReaderxr=sp.getXMLReader();MyXMLHandlermHandler=newMyXMLHandler();xr.setContentHandler(mHandler);xr.pa

以前,我使用自定义TrustManager谈论过here来做到这一点

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发送用于Gzip压缩的Accept-EnCoding标头.我可以这样

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?另外,还有更好的方法吗? (是否需要首先检查以确保手机确实可以接受我说可以的压缩后的网页?)

解决方法:

如果要使用Apache http客户端API,可以通过扩展DefaulthttpClIEnt继续使用自定义TrustManager.

import org.apache.http.conn.ssl.SSLSocketFactory;public class MyhttpClIEnt extends DefaulthttpClIEnt {  final Context context;  public MyhttpClIEnt(Context context) {    this.context = context;  }  @OverrIDe   protected ClIEntConnectionManager createClIEntConnectionManager() {    SchemeRegistry registry = new SchemeRegistry();    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));    registry.register(new Scheme("https", newSslSocketFactory(), 443));    return new SingleClIEntConnManager(getParams(), registry);  }  private SSLSocketFactory newSslSocketFactory() {    try {      TrustManager tm = new MyCustomTrustManager();      SSLContext ctx = SSLContext.getInstance("TLS");      ctx.init(null, new TrustManager[] {tm}, null);      SSLSocketFactory sf = new SSLSocketFactory(ctx);      return new SSLSocketFactory(ctx);    } catch (Exception e) {      throw new Error(e);    }  }}
总结

以上是内存溢出为你收集整理的java-HttpGet /客户端和HTTPS全部内容,希望文章能够帮你解决java-HttpGet /客户端和HTTPS所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1083513.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存