1.我們的URL是GET的方式請求,那麼就是網址+?+數據(英文狀態的"?"問號),組成完整的URL,用來開啓連接。
2.android4.0要求必須把和網絡相關的操作放到子線程中。
3.使用網絡方面和流相關的都是需要拋異常(即try/catch)。
new Thread() { @Override public void run() { try { // URL url = new URL("http://192.168.0.15:8080/androidJieKou/personServlet"); URL url = new URL("http://v.juhe.cn/toutiao/index?type=&key=8b13d671c5a2c4ffb94321ea8dcab509"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setConnectTimeout(3000); httpURLConnection.setReadTimeout(3000); int responseCode = httpURLConnection.getResponseCode(); if (responseCode == httpURLConnection.HTTP_OK) { //獲取數據的輸入流 InputStream inputStream = httpURLConnection.getInputStream(); // byte[] bytes = new byte[1024]; // inputStream.read(); //字節數組輸出流,用來存儲數據(inputStream中的數據) ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int length = 0; //用while循環判斷讀取inputStream.read(bytes),如果返回-1時,則說明讀完了 while ((length = inputStream.read(bytes)) != -1) { //參數:1.字節數組(寫入來源), 2.開始下標 3.存入長度 arrayOutputStream.write(bytes, 0, length); //強制釋放緩衝區 arrayOutputStream.flush(); } // String s = arrayOutputStream.toString(); //s爲json數據字符串類型(String) } } catch (Exception e) { e.printStackTrace(); } } }.start();