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