1.概述
之前都用HttpClient,里面api很强大,用起来也很方便,但是android一直提倡使用HttpUrlConnection。查了一下度娘,发现2.2之前HttpUrlConnection有一个bug,所以没什么人会去用,但之后官方做了修复,而且还增加了缓存机制。到android6.0后,官方直接废弃了HttpClient,明确提倡了HttpUrlConnection。
2.实现
POST方法实现
<span style="white-space:pre"> </span>public static String doPost(String url, String params) {
String result = new String();
OutputStream out = null;
InputStream in = null;
try {
URL realUrl = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) realUrl.openConnection();
urlConnection.setConnectTimeout(10000);//设置连接超时
urlConnection.setReadTimeout(30000);
urlConnection.setRequestProperty("connection", "Keep-Alive");
urlConnection.setRequestMethod("POST");
// 发送POST请求必须设置如下两行
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setChunkedStreamingMode(0);
// 获取URLConnection对象对应的输出流
out = new BufferedOutputStream(urlConnection.getOutputStream());
// 发送请求参数
out.write(params.getBytes());
out.flush();
if(urlConnection.getResponseCode() == 200) {
in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buffer = new byte[in.available()];
in.read(buffer);
result = new String(buffer);
}else {
result = null;
}
} catch (Exception e) {
e.printStackTrace();
}finally{//使用finally块来关闭输出流、输入流
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
GET方法实现
<span style="white-space:pre"> </span>public static String doGet(String url) {
String result = new String();
OutputStream out = null;
InputStream in = null;
try {
URL realUrl = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) realUrl.openConnection();
urlConnection.setConnectTimeout(10000);//设置连接超时
urlConnection.setReadTimeout(30000);
urlConnection.setRequestProperty("connection", "Keep-Alive");
urlConnection.setRequestMethod("GET");
if(urlConnection.getResponseCode() == 200) {
in = new BufferedInputStream(urlConnection.getInputStream());
<span style="white-space:pre"> </span> byte[] buffer = new byte[in.available()];
<span style="white-space:pre"> </span> in.read(buffer);
<span style="white-space:pre"> </span> result= new String(buffer);
}else {
result = null;
}
} catch (Exception e) {
e.printStackTrace();
}finally{//使用finally块来关闭输出流、输入流
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}