Android中HttpUrlConnection使用步驟與總結

1.通過url的openConnection方法來開啓一個HttpURLConnection(需要強轉)。
2.設置HttpURLConnection對象的請求方式(常用的兩種請求方式:GET、POST)。
3.設置HttpURLConnection對象的連接超時時間、讀取超時時間。
4.獲取HttpURLConnection的響應碼。
5.根據響應碼來判斷(200:成功(HttpURLConnection.HTTP_OK)。
6.成功則獲取輸入流來讀取數據到字節數組(byte[])中,用while循環來判斷是否讀完,並且獲取讀取的長度。
7.通過ByteArrayOutputStream字節數組輸出流)來寫入字節數組byte[])中的數據,
8.然後我們可以將ByteArrayOutputStream轉換成字符串用於操作。


注:
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();
                                //sjson數據字符串類型(String                                
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }.start();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章