介紹
沽源ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18982081108(備注:SSL證書合作)期待與您的合作!早些時候,Android 上發(fā)送 HTTP 請求一般有 2 種方式:HttpURLConnection 和 HttpClient。不過由于 HttpClient 存在 API 數(shù)量過多、擴展困難等缺點,Android 團隊越來越不建議我們使用這種方式。在 Android 6.0 系統(tǒng)中,HttpClient 的功能被完全移除了。因此,在這里我們只簡單介紹HttpURLConnection 的使用。
代碼 (核心部分,目前只演示 GET 請求):
1. Manifest.xml 中添加網(wǎng)絡權限:<uses-permission android:name="android.permission.INTERNET">
2. 在子線程中發(fā)起網(wǎng)絡請求:
new Thread(new Runnable() { @Override public void run() { doRequest(); } }).start(); //發(fā)起網(wǎng)絡請求 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.設置連接超時和讀取超時的毫秒數(shù) 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(); } } }
文章題目:Android網(wǎng)絡技術HttpURLConnection詳解-創(chuàng)新互聯(lián)
鏈接地址:http://aaarwkj.com/article28/dohhcp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、定制開發(fā)、軟件開發(fā)、網(wǎng)頁設計公司、虛擬主機、面包屑導航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容