2011年1月11日 星期二

獲取 https 連結內容

最近在 Android 上需要介接一些 https protocol 的 API
大部份和登入與授權有關,比如 facebook、plurk 等登入 API
所以記錄一下與 http 連線不同之處,大概就是針對 httpClient 物件做一些額外的調整


public DefaultHttpClient getDefaultHttpClient()
{
  DefaultHttpClient hcRtn = null;

  //sets up parameters
  HttpParams params = new BasicHttpParams();
  HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(params, "utf-8");
  params.setBooleanParameter("http.protocol.expect-continue", false);

  //registers schemes for both http and https
  SchemeRegistry registry = new SchemeRegistry();
  registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();

  sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
  registry.register(new Scheme("https", sslSocketFactory, 443));

  ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
  hcRtn = new DefaultHttpClient(manager, params);
  return hcRtn;
}

public static void main(String[] args)
{
  DefaultHttpClient httpClient = getDefaultHttpClient();

  Document doc = MyHttpUtils.getDocument(httpClient, "https://ooxx.ooxx.ooxx");

  httpClient.getConnectionManager().shutdown();
}

沒有留言:

張貼留言