HttpClient是早期Android提供可以用來與WebServer溝通的API
Android2.3之後就建議使用新的HttpURLConnection,這裡我就不在贅述
有關HttpClient與新版的HttpURLConnection差別
請直接看上一篇HttpsURLConnection實作HTTPs與強制允許自簽憑證(Self-Signed Certificate)
不多說,就直接看Code吧:
SchemeRegistry schemeRegistry = new SchemeRegistry(); // http scheme schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // https scheme schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); HttpParams params = new BasicHttpParams(); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); HttpClient client = new DefaultHttpClient(cm, params); final HttpPost post = new HttpPost("https://127.0.0.1/login.php"); post.setHeader("Connection", "Keep-Alive"); post.setHeader("Content-Type", "multipart/form-data"); /*以下省略*/
其中缺的EasySSLSocketFactory與EasyX509TrustManager可以直接點選連結後複製
因為這兩隻程式有使用Apache的License,因此我就不貼上來了。
Place your comment