国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > Android > 正文

Android網(wǎng)絡(luò)技術(shù)HttpURLConnection詳解

2019-12-12 02:21:47
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

介紹

早些時(shí)候,Android 上發(fā)送 HTTP 請(qǐng)求一般有 2 種方式:HttpURLConnection 和 HttpClient。不過(guò)由于 HttpClient 存在 API 數(shù)量過(guò)多、擴(kuò)展困難等缺點(diǎn),Android 團(tuán)隊(duì)越來(lái)越不建議我們使用這種方式。在 Android 6.0 系統(tǒng)中,HttpClient 的功能被完全移除了。因此,在這里我們只簡(jiǎn)單介紹HttpURLConnection 的使用。
代碼 (核心部分,目前只演示 GET 請(qǐng)求):

 1. Manifest.xml 中添加網(wǎng)絡(luò)權(quán)限:<uses-permission android:name="android.permission.INTERNET">

2. 在子線程中發(fā)起網(wǎng)絡(luò)請(qǐng)求:

new Thread(new Runnable() {          @Override          public void run() {            doRequest();          }        }).start();//發(fā)起網(wǎng)絡(luò)請(qǐng)求        private void doRequest() {  HttpURLConnection connection = null;  BufferedReader reader = null;  try {    //1.獲取 HttpURLConnection 實(shí)例.注意要用 https 才能獲取到結(jié)果!    URL url = new URL("https://www.baidu.com");    connection = (HttpURLConnection) url.openConnection();    //2.設(shè)置 HTTP 請(qǐng)求方式    connection.setRequestMethod("GET");    //3.設(shè)置連接超時(shí)和讀取超時(shí)的毫秒數(shù)    connection.setConnectTimeout(5000);    connection.setReadTimeout(5000);    //4.獲取服務(wù)器返回的輸入流    InputStream inputStream = connection.getInputStream();    //5.對(duì)獲取的輸入流進(jìn)行讀取    reader = new BufferedReader(new InputStreamReader(inputStream));    final StringBuilder response = new StringBuilder();    String line;    while ((line = reader.readLine()) != null) {      response.append(line);    }    //然后處理讀取到的信息 response。返回的結(jié)果是 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 版》

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 宁远县| 呼伦贝尔市| 化隆| 宁波市| 三门县| 德州市| 佛坪县| 平泉县| 武川县| 岫岩| 鸡西市| 湘阴县| 拜泉县| 汝城县| 门头沟区| 浙江省| 昌吉市| 南安市| 普兰店市| 通道| 恭城| 无极县| 永修县| 莲花县| 平度市| 纳雍县| 邵阳市| 鱼台县| 上饶市| 上虞市| 红桥区| 孝感市| 怀安县| 巴南区| 清丰县| 宝兴县| 大新县| 会泽县| 新泰市| 乌审旗| 泸西县|