2014年12月7日 星期日

[Android] DefaultHttpClient Https 失效 取回值為空

在使用 org.apache.http.impl.client.DefaultHttpClient; 呼叫api時

本來是可以正常回傳資訊內容

不過有時候回傳的值為空

後來發現原來是因為 api 的 通訊協定是 https 造成



解決方式:

必須註冊 https 通訊協定
  String response = "";
  try 
  //需註冊https 443 port,否則https會無效
   SchemeRegistry schemeRegistry = new SchemeRegistry();
   schemeRegistry.register(new Scheme("https", 
               SSLSocketFactory.getSocketFactory(), 443));
  HttpParams params = new BasicHttpParams();
   SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry);
   
   for (String url : arg0) {
    DefaultHttpClient client = new DefaultHttpClient(mgr, params);
    HttpGet httpGet = new HttpGet(url);
    HttpResponse execute = client.execute(httpGet);
    InputStream content = execute.getEntity().getContent();
    BufferedReader buffer = new BufferedReader(
      new InputStreamReader(content));
    String s = "";
    while ((s = buffer.readLine()) != null) {
     response += s;
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return response;

參考連結:

http://stackoverflow.com/questions/2603691/android-httpclient-and-https

沒有留言:

張貼留言