安卓原生App开发时常用的http开发工具
- 系统内置http请求工具为 HttpURLConnection
- httpClient 是 apache 的开源工具
- okHttp 使用更简单,语法相对HttpURLConnection也简洁了许多,需要在graddle添加依赖。
本文主要讲解如何使用HttpURConnection向服务器发送Reqest, 保存Response内容,如何上传文件等内容。
1. 使用 HttpURLConnection 发送http GET请求
step-1: 创建1个URL 对象
URL url = new URL("http://www.yahoo.com");
step-2: 创建1个 HttpURLConnection对象,并绑定URL对象 object,
HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
step-3: 设置请求方法,以及其它必要选项
httpConn.setConnectTimeout(10000);
httpConn.setRequestMethod("GET");
设置了请求方法后,就开始发送
step-4: 读取 Response
在httpConn对象上打开1个input stream, 用BufferReader的方式从httpConnect中读字节
InputStream inputStream = httpConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//保存response内容
StringBuffer readTextBuf = new StringBuffer();
String line = bufferedReader.readLine();
while(line != null) {
readTextBuf.append(line);
// Continue to read text line.
line = bufferedReader.readLine();
}
step-5: 读完response以后,此连接就不需要了,别忘了关闭连接
httpConn.disconnect();
2. 发送 POST请求步骤
与GET请求步骤不同在于,POST 需要在消息体内携带请求参数,因此要在httpConn连接上打开ouput stream,才能发出
将第1节的step-3 改为如下:
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty(“Key”,”Value”);
httpConn.setDoOutput(true);
Output the stream to the server
OutputStream outputPost = new BufferedOutputStream(httpConn.getOutputStream());
writeStream(outputPost);
outputPost.flush();
outputPost.close();

本文详细介绍了如何在Android原生应用中使用HttpURLConnection进行GET和POST请求,包括发送JSON数据和文件上传,以及不同请求方法的区别和所需设置的请求头。
1万+

被折叠的 条评论
为什么被折叠?



