一塊兒學Android之Http訪問

概述

在Android開發中,通常經過網絡進行訪問服務器端的信息(存儲和檢索網絡中的數據),如API接口,WebService,網絡圖片等。今天主要講解Http訪問的經常使用方法,僅供學習分享使用。html

涉及知識點

  1. URL 表示互聯網位置的統一資源標識符。
  2. HttpURLConnection 表示一個URL的Http鏈接,是一個抽象類,經過URL中的 openConnection()實例化一個鏈接對象。
  3. setConnectTimeout(5000) 設置超時時間,setRequestMethod("GET") 設置訪問方式。
  4. getResponseCode() 獲取返回碼,如200表示成功。
  5. getInputStream() 返回讀取到數據的字節流; getOutputStream() 返回往指定URL寫入數據的字節流。
  6. ByteArrayOutputStream 數組和輸出流之間的轉換。
  7. WebView 用於顯示Web Page的一個控件,經過loadDataWithBaseURL(String baseUrl, String data,String mimeType, String encoding, String historyUrl)加載內容。

Http訪問步驟

  1. 建立一個URL對象: URL url = new URL(https://www.baidu.com);
  2. 調用URL對象的openConnection( )來獲取HttpURLConnection對象實例: HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  3. 設置HTTP請求使用的方法:GET或者POST,或者其餘請求方式好比:PUT conn.setRequestMethod("GET");
  4. 設置鏈接超時,讀取超時的毫秒數,以及服務器但願獲得的一些消息頭 conn.setConnectTimeout(6*1000); conn.setReadTimeout(6 * 1000);
  5. 調用getInputStream()方法得到服務器返回的輸入流,而後輸入流進行讀取了 InputStream in = conn.getInputStream();
  6. 最後調用disconnect()方法將HTTP鏈接關掉 conn.disconnect();

示例圖

以下圖所示:android

核心代碼

獲取數據類web

 1 /**
 2  * Created by hex on 2019/4/6.
 3  */
 4 public class GetData {
 5     // 定義一個獲取網絡圖片數據的方法:
 6     public static byte[] getImage(String path) throws Exception {
 7         URL url = new URL(path);
 8         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 9         // 設置鏈接超時爲5秒
10         conn.setConnectTimeout(5000);
11         // 設置請求類型爲Get類型
12         conn.setRequestMethod("GET");
13         // 判斷請求Url是否成功
14         if (conn.getResponseCode() != 200) {
15             throw new RuntimeException("請求url失敗");
16         }
17         InputStream inStream = conn.getInputStream();
18         byte[] bt = StreamTool.read(inStream);
19         inStream.close();
20         return bt;
21     }
22 
23     // 獲取網頁的html源代碼
24     public static String getHtml(String path) throws Exception {
25         URL url = new URL(path);
26         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
27         conn.setConnectTimeout(5000);
28         conn.setRequestMethod("GET");
29         if (conn.getResponseCode() == 200) {
30             InputStream in = conn.getInputStream();
31             byte[] data = StreamTool.read(in);
32             String html = new String(data, "UTF-8");
33             return html;
34         }
35         return null;
36     }
37 }

InputStream轉換爲byte[]功能數組

 1 /**
 2  * Created by Administrator on 2019/4/6.
 3  */
 4 public class StreamTool {
 5     //從流中讀取數據
 6     public static byte[] read(InputStream inStream) throws Exception {
 7         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
 8         byte[] buffer = new byte[1024];
 9         int len = 0;
10         while ((len = inStream.read(buffer)) != -1) {
11             outStream.write(buffer, 0, len);
12         }
13         inStream.close();
14         return outStream.toByteArray();
15     }
16 }

刷新界面賦值服務器

 1 // 用於刷新界面
 2     private Handler handler = new Handler() {
 3         public void handleMessage(android.os.Message msg) {
 4             switch (msg.what) {
 5                 case 0x001:
 6                     hideAllWidget();
 7                     imgPic.setVisibility(View.VISIBLE);
 8                     imgPic.setImageBitmap(bitmap);
 9                     Toast.makeText(MainActivity.this, "圖片加載完畢", Toast.LENGTH_SHORT).show();
10                     break;
11                 case 0x002:
12                     hideAllWidget();
13                     scroll.setVisibility(View.VISIBLE);
14                     txtshow.setText(detail);
15                     Toast.makeText(MainActivity.this, "HTML代碼加載完畢", Toast.LENGTH_SHORT).show();
16                     break;
17                 case 0x003:
18                     hideAllWidget();
19                     webView.setVisibility(View.VISIBLE);
20                     webView.loadDataWithBaseURL("", detail, "text/html", "UTF-8", "");
21                     Toast.makeText(MainActivity.this, "網頁加載完畢", Toast.LENGTH_SHORT).show();
22                     break;
23                 default:
24                     break;
25             }
26         }
27 
28         ;
29     };

若是要訪問網絡,還須要有相應的權限網絡

1  <uses-permission android:name="android.permission.INTERNET" />

 

備註

關於Http訪問的相關知識還有不少,本文知識簡單粗略的講解,但願拋磚引玉,共同窗習。ide

相關文章
相關標籤/搜索