Android网络编程之HttpURLConnection应用-快递查询案例(GET、POST、JSON、Handler等简单应用~)

前言

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

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

部分代码

  • 主界面
    www.srblog.cn
  • 这里主要介绍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();
    }

 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
    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+"");
           }
        }
    };

动图演示

www.srblog.cn

项目源码

等待上传中~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值