以前,我使用自定义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所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)