介紹
早些時候,Android 上發送 HTTP 請求一般有 2 種方式:HttpURLConnection 和 HttpClient。不過由于 HttpClient 存在 API 數量過多、擴展困難等缺點,Android 團隊越來越不建議我們使用這種方式。在 Android 6.0 系統中,HttpClient 的功能被完全移除了。因此,在這里我們只簡單介紹HttpURLConnection 的使用。
代碼 (核心部分,目前只演示 GET 請求):
1. Manifest.xml 中添加網絡權限:<uses-permission android:name="android.permission.INTERNET">
2. 在子線程中發起網絡請求:
new Thread(new Runnable() { @Override public void run() { doRequest(); } }).start(); //發起網絡請求 private void doRequest() { HttpURLConnection connection = null; BufferedReader reader = null; try { //1.獲取 HttpURLConnection 實例.注意要用 https 才能獲取到結果! URL url = new URL("https://www.baidu.com"); connection = (HttpURLConnection) url.openConnection(); //2.設置 HTTP 請求方式 connection.setRequestMethod("GET"); //3.設置連接超時和讀取超時的毫秒數 connection.setConnectTimeout(5000); connection.setReadTimeout(5000); //4.獲取服務器返回的輸入流 InputStream inputStream = connection.getInputStream(); //5.對獲取的輸入流進行讀取 reader = new BufferedReader(new InputStreamReader(inputStream)); final StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } //然后處理讀取到的信息 response。返回的結果是 HTML 代碼,字符非常多。 runOnUiThread(new Runnable() { @Override public void run() { tvResponse.setText(response.toString()); } }); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } }
效果圖:
源碼下載地址:HttpURLConnection
本例子參照《第一行代碼 Android 第 2 版》
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。