温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android网络技术HttpURLConnection详解

发布时间:2020-10-01 06:37:04 来源:脚本之家 阅读:112 作者:卡麦哈麦哈 栏目:移动开发

介绍

早些时候,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();
    }
  }
}

效果图:

Android网络技术HttpURLConnection详解

源码下载地址:HttpURLConnection

本例子参照《第一行代码 Android 第 2 版》

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI