HttpGet / Client和HTTPS

时间:2011-05-05 08:58:53

标签: java android https

以前,我使用自定义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的字符串),它可以正常工作。但是,我现在想要为gzip压缩发送相同的url一个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压缩网页?)

2 个答案:

答案 0 :(得分:3)

如果您想使用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);
    }
  }
}

答案 1 :(得分: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));

我仍然不确定这是最好的解决方案,所以如果有人有更好的想法,我会稍微提出这个问题。 :)