亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2017年07月31日 15:51:35   作者:卡麥哈麥哈  
這篇文章主要為大家詳細(xì)介紹了Android網(wǎng)絡(luò)技術(shù)HttpURLConnection的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

介紹

早些時(shí)候,Android 上發(fā)送 HTTP 請(qǐng)求一般有 2 種方式:HttpURLConnection 和 HttpClient。不過由于 HttpClient 存在 API 數(shù)量過多、擴(kuò)展困難等缺點(diǎn),Android 團(tuán)隊(duì)越來越不建議我們使用這種方式。在 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í)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論