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

前言

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");//设置请求方式为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();
}
  • JSON数据的解析
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;
}
  • 使用Handler更新UI
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+"");
}
}
};

动图演示

项目源码

等待上传中~


Android网络编程之HttpURLConnection应用-快递查询案例
https://www.srblog.cn/posts/660e61a1/
作者
sr
发布于
2018年12月6日
许可协议