2011-05-05 77 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)); 

我仍然不不過,這確實是最好的解決方案,所以如果有人有更好的想法,我會留下一些問題。 :)