2018-12-26
2018-12-26 本文已影响0人
ShaMeless_2190
由于安卓已经抛弃了HttpClient 网络请求。现在写一下HttpURLConnection网络请求
HttpClient是apache的开源框架,封装了访问http的请求头,参数,内容体,响应等等,使用起来比较方便,而HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。
从稳定性方面来说的话,HttpClient很稳定,功能强,BUG少,容易控制细节,而之前的HttpURLConnection一直存在着版本兼容的问题,不过在后续的版本中已经相继修复掉了。
从上面可以看出之前一直使用HttClient是由于HttpURLConnection不稳定导致,那么现在谷歌虽然修复了HttpURLConnection之前存在的一些问题之后,相比HttpClient有什么优势呢?为何要废除HttpClient呢?
HttpUrlConnection是Android SDK的标准实现,而HttpClient是apache的开源实现;
HttpUrlConnection直接支持GZIP压缩;HttpClient也支持,但要自己写代码处理;
HttpUrlConnection直接支持系统级连接池,即打开的连接不会直接关闭,在一段时间内所有程序可共用;HttpClient当然也能做到,但毕竟不如官方直接系统底层支持好;
HttpUrlConnection直接在系统层面做了缓存策略处理,加快重复请求的速度。
GET请求
private String requestGet(HashMap<String, String> paramsMap) throws Exception {
StringBuffer tempParams = new StringBuffer();
int pos=0;
for (String key : paramsMap.keySet()) {
if (pos>0){
tempParams.append("$");
}
tempParams.append(String.format("%s=%s",key,URLEncoder.encode(paramsMap.get(key),"utf-8")));
pos++;
}
String requestUrl=baseUrl+tempParams;
URL url = new URL(requestUrl);
HttpURLConnection urlConnection = (HttpURLConnection ) url.openConnection();
urlConnection.setConnectTimeout(1000*5);// 设置连接主机超时时间
urlConnection.setReadTimeout(1000*5);//设置从主机读取数据超时
urlConnection.setUseCaches(true);// 设置是否使用缓存 默认是true
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.addRequestProperty("Connection", "Keep-Alive");//设置客户端与服务连接类型
urlConnection.connect();
if (urlConnection.getResponseCode()==200){
InputStream in = urlConnection.getInputStream();
String requestStr = streamToString(in);
urlConnection.disconnect();
return requestStr;
}
urlConnection.disconnect();
return null;
}
POST请求
/**
* POST请求
* @param map
* @return
* @throws Exception
*/
public String postRequset( HashMap<String,String> map) throws Exception {
StringBuffer stringBuffer = new StringBuffer();
URL requestUrl = new URL(baseUrl);
HttpURLConnection urlConnection = (HttpURLConnection) requestUrl.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(1000*5);
urlConnection.setReadTimeout(1000*5);
//发送post请求必须设置
// Post请求必须设置允许输出 默认false
urlConnection.setDoOutput(true);
//设置请求允许输入 默认是true
urlConnection.setDoInput(true);
// Post请求不能使用缓存
urlConnection.setUseCaches(false);
urlConnection.setInstanceFollowRedirects(true);//设置本次连接是否自动处理重定向
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 配置请求Content-Type
urlConnection.connect();
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
StringBuilder request = new StringBuilder();
//合成参数
StringBuilder tempParams = new StringBuilder();
int pos = 0;
for (String key : map.keySet()) {
if (pos > 0) {
tempParams.append("&");
}
tempParams.append(String.format("%s=%s", key, URLEncoder.encode(map.get(key),"utf-8")));
pos++;
}
String params =tempParams.toString();
out.writeBytes(params);
out.flush();
out.close();
if (urlConnection.getResponseCode() == 200) {
String sb = streamToString(urlConnection.getInputStream());
urlConnection.disconnect();
return sb;
}
urlConnection.disconnect();
return null;
}
/**
* 从inputstreem读取数据
* @param in
* @return
* @throws IOException
*/
public String streamToString(InputStream in) throws IOException {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len =0;
while ((len=in.read(buffer))!=-1){
bs.write(buffer,0,len);
}
bs.close();
in.close();
byte[] bytes = bs.toByteArray();
return new String(bytes);
}