HttpURLConnection是一种多用途、轻量极的HTTP客户端。它的API简单,体积较小,因而非常适用于Android项目,压缩和缓存机制可以有效地减少网络访问的流量,在提升速度和省电方面也起到了较大的作用,使用它来进行HTTP操作可以适用于大多数的应用程序。HttpUrlConnection是Android SDK的标准实现,直接支持系统级连接池,即打开的连接不会直接关闭,在一段时间内所有程序可共用;直接在系统层面做了缓存策略处理,加快重复请求的速度
本文将以一个查询快递信息的案例来介绍,包括GET,POST两中方式请求网络资源,解析JSON数据,Handler异步消息处理机制等应用~
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();
}
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+"");
}
}
};
等待上传中~