Android - HttpClient & HttpConnection
Android 連線有很多連法,
根據這篇文章
https://read01.com/oA3QzQ.html
我只取兩個出來玩
因為公司用android連測試伺服會出錯,也不知道原因
想說會不會程式用法不一樣而導致,結果差不多
但還是寫了兩個測試範例
HttpConnection
public static void httpConnectionTest() { HttpURLConnection httpUrlConnection = null; try { URL url = new URL(apiUrl); httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setRequestMethod("POST"); httpUrlConnection.setConnectTimeout(10000); httpUrlConnection.setReadTimeout(10000); httpUrlConnection.setDoInput(true); //允許輸入流,即允許下載 httpUrlConnection.setDoOutput(true); //允許輸出流,即允許上傳 httpUrlConnection.setUseCaches(false); //設置是否使用緩存 List<NameValuePair> params = new ArrayList<NameValuePair>(); OutputStream os = httpUrlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(params)); writer.flush(); writer.close(); os.close(); //Get Response InputStream is = httpUrlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); response.append('\r'); } reader.close(); Log.e("deubg","response = " + response); Log.e("deubg","http connection success"); }catch (Exception ex) { Log.e("deubg","exception " + ex.toString()); ex.printStackTrace(); }finally { if(httpUrlConnection!=null) { httpUrlConnection.disconnect(); } } }
HttpClient
public static void httpClientTest(){ List<NameValuePair> params = new ArrayList<NameValuePair>(); Iterator<NameValuePair> iterator = params.iterator(); JSONObject jsonObjectTmp = null; HttpPost request = new HttpPost(apiUrl); request.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); // 请求超时 request.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);// 读取超时 HttpResponse response ; try { request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); response = new DefaultHttpClient().execute(request); if(response.getStatusLine().getStatusCode() == 200 ){ String data = EntityUtils.toString(response.getEntity(),"UTF-8"); Log.e("deubg","out put = " + data); } } catch (Exception e){ Log.e("deubg","exception ex = " + e.toString()); e.printStackTrace(); } }
但兩個回傳的錯誤訊息不太相同
HttpConnection 得到的錯誤訊息為
java.net.SocketTimeoutException: failed to connect to....
HttpClient 得到的錯誤訊息為
org.apache.http.conn.ConnectTimeoutException: Connect to
所以還是無解……