本篇继续介绍关于OkHttp的其他使用姿势。
1.OkHttp结合gson使用:其中ResponseBody.charStream()使用Content-Type响应头来选择在解码响应正文时要使用的字符集。 如果没有指定字符集,它默认为UTF-8。
private void Test5() throws IOException {
OkHttpClient client = new OkHttpClient();
Gson gson = new Gson();
Request request = new Request.Builder().url("https://api.github.com/gists/c2a7c39532239ff261be").build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Git git = gson.fromJson(response.body().charStream(), Git.class);
for (Map.Entry<String, GitFile> entry : git.files.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue().content);
}
}
class Git {
Map<String, GitFile> files;
}
class GitFile {
String content;
}
2.拦截器的使用:
okHttp中注册的拦截器可以分成两类,分别是程序拦截器和网络拦截器。两者最大的不同就是程序拦截器只会对网络请求调用一次,然后拦截器返回的数据会直接从缓存中读取;而网络拦截器会进行两次的网络请求。
首先是注册程序拦截器:
/**
* Created by BeautifulSoup on 2017/3/1.
* 记录日志拦截器
*/
public class AddLogInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request=chain.request();
long startTime=System.nanoTime();
Log.i("AddLogInterceptor:",String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response=chain.proceed(request);//放行
long endTime=System.nanoTime();
Log.i("AddLogInterceptor","请求的时间是:"+(endTime-startTime)/1e6d+",响应的连接是:"+response.request().url()+",响应头是:"+response.headers());
return response;
}
}
private static final MediaType MEDIA_TYPE_MAKEDOWN=MediaType.parse("text/x-markdown;charset=UTF-8");
OkHttpClient client3=builder.addInterceptor(new AddLogInterceptor()).build();
//使用POST提交请求,参数封装在请求体中
String postBody = ""
+ "Releases\n"
+ "--------\n"
+ "\n"
+ " * _1.0_ May 6, 2017\n"
+ " * _1.1_ June 15, 2017\n"
+ " * _1.2_ August 11, 2017\n";
Request request3=new Request.Builder().url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MAKEDOWN,postBody))
.build();
client3.newCall(request3).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println(response.body().string());
}
});
网络拦截器的注册和程序拦截器的注册基本一致,唯一不同之处:
OkHttpClient client3=builder.addNetworkInterceptor(new AddLogInterceptor()).build();