HttpURLConnection简单介绍
在 Android 2.2 及其之前的版本中,HtpURLConnection 一直存在着一些令人厌烦的 bug。比如对一个可读的 InputStream 调用 close 方法时,就有可能会导致连接池失效。因此,在 Android 2.2 及其之前的版本中,使用 HtpCient 是较好的选择;而在 Android 2.3版本及之后的版本中,使用 HttpURLConnection 则是最佳的选择。HttpURL Connection 的 API简单,体积较小,因而非常适用于 Android 项目。HttpURLConnection 的压缩和缓存机制可以有效地减少网络访问的流量,在提升速度和省电方面也起到了较大的作用。另外在 Android 6.0 版本中,HtpClent 库被移除了,如果不引用 HtpClient, HttpURL Connection 则是我们唯一的选择
权限配置
<uses-permission android:name="android.permission.INTERNET"/>
首先我们创建一个UrlConnManager类,在这个类里面提供一个getHttpURLConnection方法用来配置默认参数并返回HttpURLConnection,代码如下所示:
public static HttpURLConnection getHttpUrlConnection(String url) {
HttpURLConnection mHttpUrlConnection = null;
try {
URL mUrl = new URL(url);
mHttpUrlConnection = (HttpURLConnection) mUrl.openConnection();
mHttpUrlConnection.setConnectTimeout(15000);
mHttpUrlConnection.setReadTimeout(15000);
mHttpUrlConnection.setRequestMethod("POST");
mHttpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
mHttpUrlConnection.setDoInput(true);
mHttpUrlConnection.setDoOutput(true);
} catch (IOException e) {
e.printStackTrace();
}
return mHttpUrlConnection;
}
因为要发送的是POST请求,所以在UrlConnManager类中再写一个postParams方法,用来组装POST请求参数,将请求参数写入输出流,代码如下所示:
public static void postParams(OutputStream output, Map<String, String> map) {
try {
StringBuilder mStringBuilder = new StringBuilder();
for (String key : map.keySet()) {
if (!mStringBuilder.toString().isEmpty()) {
mStringBuilder.append("&");
}
mStringBuilder.append(URLEncoder.encode(key, "UTF-8"));
mStringBuilder.append("=");
mStringBuilder.append(URLEncoder.encode(map.get(key), "UTF-8"));
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output,
StandardCharsets.UTF_8));
writer.write(mStringBuilder.toString());
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
然后我们添加请求参数,调用postParams方法将请求的参数组织好并传给HttpURLConnection的输出流,请求连接并处理返回的结果。这里访问某宝IP库,代码如下所示:
private static void useHttUrlConnectionPost(String url) {
InputStream inputStream = null;
HttpURLConnection mHttpUrlConnection = getHttpUrlConnection(url);
try {
Map<String, String> map = new HashMap<>();
map.put("ip", "59.108.54.37");
postParams(mHttpUrlConnection.getOutputStream(), map);
mHttpUrlConnection.connect();
inputStream = mHttpUrlConnection.getInputStream();
int code = mHttpUrlConnection.getResponseCode();
String respose = MyHttpClientUtils.converStreamToString(inputStream);
System.out.println("请求状态码:" + code + "\n请求结果:\n" + respose);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
最后开启线程请求某宝的IP库,如下所示:
new Thread(() -> {
useHttUrlConnectionPost("http://ip.*****.com/service/getIpInfo.php");
}).start();
备注
*****:taobao
特别感谢:刘望舒的著作(Android进阶之光第2版)