前言
HttpURLConnection是一种多用途、轻量极的HTTP客户端。它的API简单,体积较小,因而非常适用于Android项目,压缩和缓存机制可以有效地减少网络访问的流量,在提升速度和省电方面也起到了较大的作用,使用它来进行HTTP操作可以适用于大多数的应用程序。HttpUrlConnection是Android SDK的标准实现,直接支持系统级连接池,即打开的连接不会直接关闭,在一段时间内所有程序可共用;直接在系统层面做了缓存策略处理,加快重复请求的速度
本文将以一个查询快递信息的案例来介绍,包括GET,POST两中方式请求网络资源,解析JSON数据,Handler异步消息处理机制等应用~
部分代码
- 主界面
- 这里主要介绍GET和POST两种网络请求方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| 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"); 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(); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| 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(); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 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; }
|
1 2 3 4 5 6 7 8 9 10 11 12
| 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+""); } } };
|
动图演示
项目源码
等待上传中~