OkHttp 快速使用
Square-OkHttp 是一个基于 Java 的 HTTP 网络操作框架,可以提供比 JDK 的 URLConnection 更加强大的功能,同时在使用上比 Apache-HttpClient 更加简便高效;
OkHttp 支持 HTTP 的 CRUD 方法(POST,GET,PUT,DELETE 等),支持 HTTP/2 、SPDY,同时也提供了对 HTTP 的缓存机制,进一步提供 HTTP 连接效率;
OkHttp 项目主页:http://square.github.io/okhttp/
参考文档: https://www.ibm.com/developerworks/cn/java/j-lo-okhttp/index.html
使用 OkHttp 需要导入的依赖:
com.squareup.okhttp3:okhttp (3.x版本)
以下示例都是基于 OkHttp 3.X 版本,和 2.X 版本部分代码不同;
发送 GET 请求
OkHttpClient httpClient = new OkHttpClient();
//构建 Request 请求对象
Request request = new Request.Builder()
.url("http://blog.csdn.net/")
//.header("User-Agent","Chrome/58.0.3029.110") //添加请求头
.build();
// 运行httpClient,获取 Response 响应对象
Response response = httpClient.newCall(request).execute();
if(!response.isSuccessful()) {
throw new IOException("server connection error");
}
//获取所有响应头
Headers headers = response.headers();
for(int i=0; i
发送 POST 请求
提交键表单键值对
OkHttpClient httpClient = new OkHttpClient();
//构建 Request 请求对象
RequestBody formBody = new FormBody.Builder()
.add("username","assad")
.add("password","1234")
.build();
Request request = new Request.Builder()
.url("http://127.0.0.1:8080/loginCheck")
.post(formBody)
.build();
//获取 Response 对象
Response response = httpClient.newCall(request).execute();
if(!response.isSuccessful())
throw new IOException("server connection error");
//以字符串的形式获取响应正文
System.out.println(response.body().string());
提交文本正文
OkHttpClient httpClient = new OkHttpClient();
//构建 Request 请求对象
RequestBody postBody = RequestBody.create(MediaType.parse("text/plain"),"Hello world!");
Request request = new Request.Builder()
.url("http://www.baidu.com")
.post(postBody)
.build();
//获取 Response 对象
Response response = httpClient.newCall(request).execute();
if(response.isSuccessful())
throw new IOException("server connection error");
System.out.println(response.body().string());
当正文文本长度比较长时,可以使用输入流添加 reqeustBody 以节约内存,如下:
OkHttpClient httpClient = new OkHttpClient();
//使用输入流的方式构建 RequestBody
RequestBody postBody = new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.parse("text/plain");
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8("This is a long length text content");
}
};
//构建 Request 请求对象
Request request = new Request.Builder()
.url("http://www.baidu.com")
.post(postBody)
.build();
//获取 Response 对象
Response response = httpClient.newCall(request).execute();
if(response.isSuccessful())
throw new IOException("server connection error");
System.out.println(response.body().string());
提交 json 正文
提交 json 正文类似提交文本正文,只需要修改相应的请求头即可;
String jsonStr = "{\"user\":\"assad\",\"id\":2333331010}";
OkHttpClient httpClient = new OkHttpClient();
//构建 Request 请求对象
RequestBody postBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),jsonStr);
Request request = new Request.Builder()
.url("http://127.0.0.1:8080/exchangeJsonTest")
.post(postBody)
.build();
//获取 Response 对象
Response response = httpClient.newCall(request).execute();
if(response.isSuccessful())
throw new IOException("server connection error");
System.out.println(response.body().string());
文件上传
OkHttpClient httpClient = new OkHttpClient();
//构建 Multipart 类型 RequestBody,上传图片(如果需要上传多个文件,只需要添加多个addFormDataPart即可)
RequestBody postBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("files",null, new MultipartBody.Builder()
.addPart(Headers.of("Content-Disposition","form-data; uploadfilename=\"testImg.png\""),
RequestBody.create(MediaType.parse("image/png"),new File("./testImg.png")))
.build())
.build();
//构建 Request 请求对象
Request request = new Request.Builder()
.url("http://127.0.0.1:8080/getImage")
.post(postBody)
.build();
//获取 Response 对象
Response response = httpClient.newCall(request).execute();
if(response.isSuccessful())
throw new IOException("server connection error");
System.out.println(response.body().string());
文件下载
OkHttpClient httpClient = new OkHttpClient();
//构建 Request 请求对象
Request request = new Request.Builder()
.url("http://wx2.sinaimg.cn/mw600/dac9e610ly1fnzld0k3j4j20rs12wjw6.jpg")
.build();
// 运行httpClient,获取 Response 响应对象
Response response = httpClient.newCall(request).execute();
if(!response.isSuccessful()) {
throw new IOException("server connection error");
}
//以字节流的形式读取响应二进制正文,并保存为文件
BufferedInputStream input = new BufferedInputStream(response.body().byteStream());
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream("download.jpg"));
int bytes;
while(( bytes = input.read()) != -1)
output.write(bytes);
input.close();
output.flush();
output.close();