2011-05-05 45 views
3

以前,我用定义TrustManager谈到here为此HTTPGET /客户端和HTTPS

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?或者,有没有更好的方法来做到这一点? (而且是有什么,我需要先进行检查,以确保手机真的能接受,我说它能对gzip压缩的网页?)

回答

3

如果你想使用Apache HTTP客户端API,你可以继续使用自定义的TrustManager通过扩展DefaultHttpClient

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); 
    } 
    } 
} 
+0

哦,整齐,谢谢! – 2011-05-05 09:53:51

+0

我还没有测试过这个解决方案,但是它受到Bob Lee博客文章的启发http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html – Jcs 2011-05-05 09:56:00

1

其实这个作品:

URL url = new URL(buildUrlString()); 
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 
conn.setRequestProperty("Accept-Encoding","gzip"); 

InputStream instream = conn.getInputStream(); 
String response = conn.getContentEncoding(); 
if ((response != null) 
    && response.equalsIgnoreCase("gzip")) 
{ 
    instream = new GZIPInputStream(instream); 
} 
xr.parse(new InputSource(instream)); 

我仍然不不过,这确实是最好的解决方案,所以如果有人有更好的想法,我会留下一些问题。 :)