前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HttpURLConnection,HttpClient的简单使用

HttpURLConnection,HttpClient的简单使用

作者头像
专注APP开发
发布2019-11-07 11:35:00
6840
发布2019-11-07 11:35:00
举报
文章被收录于专栏:移动大前端移动大前端

HttpURLConnection

在android 2.2及以下版本中HttpUrlConnection存在着一些bug(建议使用HttpClient) 建议在android 2.3以后使用HttpUrlConnection

特点

• 比较轻便,灵活,易于扩展
• 在3.0后以及4.0中都进行了改善,如对HTTPS的支持
• 在4.0中,还增加了对缓存的支持

HttpClient(不推荐使用了)

特点

• 高效稳定,但是维护成本高昂,故android 开发团队不愿意在维护该库而是转投更为轻便的
在android2.3之后就被HttpUrlConnection取代了

OK,扯了这么多,直接开始实战。

前期准备

开发工具:Eclipse(ADT Build: v22.6.2-1085508) 开发环境:OS X EI Capitan 版本 10.11.5 搭建一个本地的测试服务用来测试访问 首先安装MAMP,用来部署测试数据:

Paste_Image.png

传送门:https://www.mamp.info/en/

配置端口

Paste_Image.png

文件部署目录

Paste_Image.png

Paste_Image.png

get_data.json文件从项目Assets目录下获取

Paste_Image.png

OK,前期准备工作完毕。

代码演示

源码地址 https://github.com/andli0626/HttpClientAndHttpUrlConnection.git 实际效果

Paste_Image.png

HttpURLConnection请求:GET 核心代码
代码语言:javascript
复制
  private void sendRequestWithHttpURLConnection() {
    // 开启线程来发起网络请求
    new Thread(new Runnable() {
     @Override
     public void run() {
      HttpURLConnection connection = null;
      try {
       // 获得URL对象
       URL url = new URL("http://www.baidu.com/");
       // 获得HttpURLConnection对象
       connection = (HttpURLConnection) url.openConnection();
       // 默认为GET请求
       connection.setRequestMethod("GET");
       // 设置 链接 超时时间
       connection.setConnectTimeout(8000);
       // 设置 读取 超时时间
       connection.setReadTimeout(8000);
       // 设置是否从HttpURLConnection读入,默认为true
       connection.setDoInput(true);
       connection.setDoOutput(true);
 
       // 请求相应码是否为200(OK)
       if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
        // 下面对获取到的输入流进行读取
        InputStream in          = connection.getInputStream();
        BufferedReader reader   = new BufferedReader(new InputStreamReader(in));
        StringBuilder  response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
         response.append(line);
        }
        Message message = new Message();
        message.what  = SHOW_RESPONSE1;
        message.obj  = response.toString();
        handler.sendMessage(message);
       }else{
        Message message = new Message();
        message.what  = SHOW_RESPONSE3;
        handler.sendMessage(message);
       }
 
      } catch (Exception e) {
             e.printStackTrace();
      } finally {
             // 关闭连接
             if (connection != null) {
              connection.disconnect();
       }
      }
     }
    }).start();
   }

HttpClient GET请求核心代码

代码语言:javascript
复制
 private void sendRequestWithHttpClient() {
   new Thread(new Runnable() {
    @Override
    public void run() {
          try {
           HttpClient httpClient = new DefaultHttpClient();
           // 指定访问的服务器地址是电脑本机
           // 注意:由于是本机测试,所以测试设备和接口必须在同一网段内,否则访问失败
           HttpGet httpGet = new HttpGet("http://192.168.0.162:8082/get_data.json");
           HttpResponse httpResponse = httpClient.execute(httpGet);
           if (httpResponse.getStatusLine().getStatusCode() == 200) {
            // 请求和响应都成功了
            HttpEntity entity = httpResponse.getEntity();
            String response = EntityUtils.toString(entity, "utf-8");
            // 解析JSON
            parseJSONWithGSON(response);
  
             Message message = new Message();
             message.what    = SHOW_RESPONSE2;
             message.obj     = response.toString();
             handler.sendMessage(message);
      }
     } catch (Exception e) {
           e.printStackTrace();
     }
    }
   }).start();
  }

参考资料

《第一行代码》 http://www.tuicool.com/articles/Yjq6niQ

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • HttpURLConnection
    • 特点
    • HttpClient(不推荐使用了)
      • 特点
      • 前期准备
      • 代码演示
      • HttpClient GET请求核心代码
      • 参考资料
      相关产品与服务
      测试服务
      测试服务 WeTest 包括标准兼容测试、专家兼容测试、手游安全测试、远程调试等多款产品,服务于海量腾讯精品游戏,涵盖兼容测试、压力测试、性能测试、安全测试、远程调试等多个方向,立体化安全防护体系,保卫您的信息安全。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档