HttpURLConnection
Sun公司提供的库,也是Java的标准类库java.net中的一员,但这个类什么都没封装,用起来很原始,若需要高级功能,则会显得不太方便,比如重访问的自定义,会话和cookie等一些高级功能。
支持HTTPS协议,以流的形式进行上传和下载,配置超时时间,IPV6,连接池等功能。
用法(android):
get方法
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Message message = new Message();
message.what = 2;
message.obj = response.toString();
handler.sendMessage(message);
} catch (IOException ex) {
Log.e("s", "Error", ex);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
).start();
设置权限
<uses-permission android:name="android.permission.INTERNET"/>
post方法
try {
url = new URL("http://api.map.baidu.com/telematics/v3/weather?");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
printWriter.write("location=%E5%98%89%E5%85%B4");//post的参数 xx=xx&yy=yy
printWriter.write("output=json");
printWriter.write("ak=5slgyqGDENN7Sy7pw29IUvr");
// flush输出流的缓冲
printWriter.flush();
//开始获取数据
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len;
byte[] arr = new byte[1024];
while((len=bis.read(arr))!= -1){
bos.write(arr,0,len);
bos.flush();
}
bos.close();
Message message = new Message();
message.what = 3;
message.obj = bos.toString("utf-8").toString();
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
谷歌在22版本之后不再支持HttpClient
因为兼容性问题,谷歌不愿意维护HttpClient,而使用HttpURLConnection
HttpURLConnection的API包小而简便,更适合安卓
HttpURLConnection能够提高速度和提升电池性能
又因为 HttpURLConnection 比较原始,所以一些第三方的框架应运而生,okhttp,retrofit,android-async-http,volley,他们的区别有时间抽空再回忆回忆