前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android网络编程之HttpURLConnection应用-快递查询案例

Android网络编程之HttpURLConnection应用-快递查询案例

作者头像
sr
发布2019-05-23 17:45:15
4820
发布2019-05-23 17:45:15
举报
文章被收录于专栏:swag codeswag code

前言

HttpURLConnection是一种多用途、轻量极的HTTP客户端。它的API简单,体积较小,因而非常适用于Android项目,压缩和缓存机制可以有效地减少网络访问的流量,在提升速度和省电方面也起到了较大的作用,使用它来进行HTTP操作可以适用于大多数的应用程序。HttpUrlConnection是Android SDK的标准实现,直接支持系统级连接池,即打开的连接不会直接关闭,在一段时间内所有程序可共用;直接在系统层面做了缓存策略处理,加快重复请求的速度

本文将以一个查询快递信息的案例来介绍,包括GET,POST两中方式请求网络资源,解析JSON数据,Handler异步消息处理机制等应用~

部分代码

  • 主界面
  • 这里主要介绍GET和POST两种网络请求方式private void doGet(final String params) { //子线程执行网络操作 new Thread(new Runnable() { @Override public void run() { try { URL url = new URL(URL_Source+"?type="+URLEncoder.encode(Param_DHL,"UTF-8")+"&postid="+URLEncoder.encode(params,"UTF-8")); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("GET");//设置请求方式为GET httpURLConnection.setReadTimeout(3000);//设置连接超时时间 if(httpURLConnection.getResponseCode() == 200){ InputStream is = httpURLConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line =""; StringBuffer result= new StringBuffer(); while((line = br.readLine()) != null){ result.append(line); } is.close(); br.close(); httpURLConnection.disconnect();//关闭连接 Message message =new Message();//创建消息体 message.what = 1; message.obj = parseData(result.toString()); handler.sendMessage(message);//发送消息体,添加到消息队列中 } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); }
代码语言:javascript
复制
private void doPost(final String params) {
       new Thread(new Runnable() {
           @Override
           public void run() {
               try {
                   URL url = new URL(URL_Source);
                   HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                   httpURLConnection.setConnectTimeout(3000);     //设置连接超时时间
                   httpURLConnection.setDoInput(true);            //打开输入流,以便从服务器获取数据
                   httpURLConnection.setDoOutput(true);           //打开输出流,以便向服务器提交数据
                   httpURLConnection.setUseCaches(false);         //禁用缓存
                   httpURLConnection.setRequestMethod("POST");
                   httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");//设置数据编码方式
                   String param ="type="+URLEncoder.encode(Param_DHL,"UTF-8") +"&postid="+URLEncoder.encode(params,"UTF-8");

                   OutputStream os = httpURLConnection.getOutputStream();
                   os.write(param.getBytes());

                   if(httpURLConnection.getResponseCode() == 200){
                       InputStream is = httpURLConnection.getInputStream();
                       BufferedReader br = new BufferedReader(new InputStreamReader(is));
                       String line ="";
                       StringBuffer result= new StringBuffer();
                       while((line = br.readLine()) != null){
                           result.append(line);
                       }
                       is.close();
                       br.close();

                       httpURLConnection.disconnect();//关闭连接
                       Message message =new Message();
                       message.what = 2;
                       message.obj = parseData(result.toString());
                       handler.sendMessage(message);

                   }
               } catch (MalformedURLException e) {
                   e.printStackTrace();
               } catch (IOException e) {
                   e.printStackTrace();
               }


           }
       }).start();
   }
  • JSON数据的解析 private String parseData(String json){ String result = ""; try { JSONObject jsonObject = new JSONObject(json); JSONArray data = jsonObject.getJSONArray("data"); //这里只取最新的一条数据显示 if(data.length()>0){ result="更新时间: "+data.getJSONObject(0).getString("time")+ "\n状态: "+data.getJSONObject(0).getString("context"); }else{ result = "该单号暂无物流进展,请稍后再试,或检查公司和单号是否有误"; } } catch (JSONException e) { e.printStackTrace(); } return result; }
  • 使用Handler更新UI
代码语言:javascript
复制
private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
       if(msg.what == 1){
           message.setText("最新状态 (GET方式)");
           info.setText(msg.obj+"");
       }else if (msg.what == 2){
           message.setText("最新状态 (POST方式)");
           info.setText(msg.obj+"");
       }
    }
};

项目源码

等待上传中~

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 部分代码
  • 项目源码
相关产品与服务
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档