一、 HttpURLConnection以GET方式訪問網絡:
HttpURLConnection connection = null;try { URL url = new URL("https://www.xxx.com/"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET");//設置訪問方式為“GET” connection.setConnectTimeout(8000);//設置連接服務器超時時間為8秒 connection.setReadTimeout(8000);//設置讀取服務器數據超時時間為8秒 if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) { //從服務器獲取響應并把響應數據轉為字符串打印 InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while (null != (line = reader.readLine())) { response.append(line); } Log.d(TAG, response.toString()); }} catch (Exception e) { e.printStackTrace();} finally { if (null!= connection) { connection.disconnect(); }}二、 HttpURLConnection以POST方式訪問網絡:
HttpURLConnection connection = null; try{ URL url = new URL("https://www.xxx.com/"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); connection.setDoOutput(true);// 使用 URL 連接進行輸出 connection.setDoInput(true);// 使用 URL 連接進行輸入 connection.setUseCaches(false);// 忽略緩存 // 建立輸出流,并寫入數據 OutputStream outputStream = connection.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeBytes("username=admin&password=888888"); dataOutputStream.close(); if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) { // 當正確響應時處理數據 StringBuffer response = new StringBuffer(); String line; BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); // 處理響應流,必須與服務器響應流輸出的編碼一致 while (null != (line = responseReader.readLine())) { response.append(line); } responseReader.close(); Log.d(TAG, response.toString()); } } catch (Exception e) { e.printStackTrace(); } finally { if (null!= connection) { connection.disconnect(); } }注意:
1. HTTP訪問是不允許在主線程進行的,否則會報錯。因此上面的操作應該在新線程中進行。
2. 一般要用HttpURLConnection.getResponseCode() == 200來判斷是否正常響應。為true則正常響應。
3. 在Android 2.2及以下版本,使用的是HttpClient,Android 2.3及以上版本,使用的是HttpURLConnection,而Android5.1之后廢棄了HttpClient的相關Api。因此HttpClient用法不再進行研究。
4. 以POST方式提交數據時,每條數據要以鍵值對的方式提交,各條數據之間以&隔開。比如上面的代碼中dataOutputStream.writeBytes(“username=admin&password=888888”);
5. 上面用到了StringBuilder和StringBuffer,沒有什么特別用意,只是順便用下。StringBuilder在單線程下比StringBuffer更高效,但不是線程安全的。
以上這篇Android 用HttpURLConnection訪問網絡的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答