之前在使用AsyncHttpClient的时候,遇到在Android6.0后找不到HttpClient的问题,后来官方更新了1.4.9版本替换了HttpClient为第三方的cz.msebera.android.httpclient。了解到Google在Android6.0后移除了HttpClient,推荐使用HttpUrlConnection实现http请求,并且许多其他第三方网络请求框架都是改为以HttpUrlConnection为基础,故此认为有必要熟悉一下其基本用法。
使用的流程:
1 | 创建URL对象 | URL url = new URL("http://qq.com"); |
2 | 实例化HttpUrlConnection对 | conn = (HttpURLConnection) url.openConnection(); |
3 | 设置请求的相关属性,post传值等 | conn.setRequestMethod("POST");conn.setDoOutput()等 |
4 | 获取返回码,判断连接成功与否 | if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) |
5 | 读取输入流 | InputStream is = conn.getInputStream(); |
6 | 关闭连接、输入流 | conn.disconnect(); is.close(); |
Get请求:
//HttpUrlConnection默认就是Get请求,最简单的情况下什么都不需要设置。
conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
Get请求示例代码:
try { URL url = new URL("http://112.124.63.181/mm/Api/Public/timestamp"); conn = (HttpURLConnection) url.openConnection(); InputStream is = conn.getInputStream(); reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } showText(sb.toString()); } catch (IOException e) { e.printStackTrace(); }finally { if (conn != null){conn.disconnect();} if (reader != null){ try { reader.close(); } catch (IOException e) {e.printStackTrace();} } }
Post请求:
Post和Get的主要区别:
conn.setRequestMethod("POST");
conn.setDoOutput(true);//允许向服务器提交数据
conn.setUseCaches(false);//Post不是用缓存
String body ="password=e10adc3949ba59abbe56e057f20f883e&username=test3";
OutputStream os = conn.getOutputStream();
os.write(body.getBytes());
os.flush();
os.close();
InputStream is = conn.getInputStream();
...
提交数据:
OutputStream os = conn.getOutputStream();
os.write(body.getBytes());
os.flush();
os.close();
直接使用低级字节流输出String转换后的字节数组。
DataOutputStream dos = new DataOutputStream(os);
OutputStreamWriter writer = new OutputStreamWriter(os);
BufferedWriter writer = new BufferedWriter(newOutputStreamWriter(os));
使用高级字符流可以相对比较方便地输出字符串、文件等。
Post请求示例代码:
String urlString = "http://120.77.156.236/mm/Api/Base/checkLogin"; String bodyString = "password=e10adc3949ba59abbe56e057f20f883e&username=test3"; URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(bodyString.getBytes("utf-8")); os.flush(); os.close(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); }
常用设置方法:
// 设置请求方法,默认是GET
conn.setRequestMethod("GET");
//设置连接服务器超时
conn.setConnectTimeout(8000);
//设置读取服务器数据超时
conn.setReadTimeout(5000);
//设置是否使用缓存
conn.setUseCaches(true);
// 设置使用的字符集
conn.setRequestProperty("Charset","UTF-8");
// 设置内容类型信息
conn.setRequestProperty("Content-Type","application/json");
// 设置自定义参数
conn.setRequestProperty("MyKey","MyValue");
//设置是否允许输出,默认为false,Post提交数据时必须为true
conn.setDoOutput
//设置是否允许输入,默认为true,这样getInputStream才有值
conn.setDoInput
//设置每次传输的流大小,防止手机内存不足
conn.setChunkedStreamingMode(51200);
//开始连接,并不需要显式调用,调用getInputStream或getResponseCode等方式时都会间接调用。
conn.connect();