OkHttp官网地址:
http://square.github.io/okhttp/
OkHttp GitHub地址:https://github.com/square/okhttp
OkHttp自我介绍:
OkHttp是一款优秀的HTTP框架,它支持get请求和post请求,支持基于Http的文件上传和下载,支持加载图片,支持下载文件透明的GZIP压缩,
支持响应缓存避免重复的网络请求,支持使用连接池来降低响应延迟问题。
配置方法
<dependency>
<groupId>com.squareup.okhttp3<groupId>
<artifactId>okhttp<artifactId>
<version>3.2.0<version>
<dependency>
基本要求
Requests(请求)
每一个HTTP请求中都应该包含一个URL,一个GET或POST方法以及Header或其他参数,当然还可以含特定内容类型的数据流。
Responses(响应)
响应则包含一个回复代码(200代表成功,404代表未找到),Header和定制可选的body。
基本使用
在日常开发中最常用到的网络请求就是GET和POST两种请求方式。
HTTP GET
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
Request是OkHttp中访问的请求,Builder是辅助类,Response即OkHttp中的响应。
Response类:
public boolean isSuccessful()
Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.
response.body()返回ResponseBody类
可以方便的获取string
public final String string() throws IOException
Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt to decode the response body as UTF-8.
Throws:
IOException
当然也能获取到流的形式:
public final InputStream byteStream()
HTTP POST
POST提交Json数据
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
f (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
使用Request的post方法来提交请求体RequestBody
POST提交键值对
OkHttp也可以通过POST方式把键值对数据传送到服务器
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody formBody = new FormEncodingBuilder()
.add("platform", "android")
.add("name", "bug")
.add("subject", "XXXXXXXXXXXXXXX")
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}