- 首先我们需要在项目中添加依赖
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
- 创建拦截器
public class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
//Chain 里包含了request和response
Request request = chain.request();
long t1 = System.nanoTime();//请求发起的时间
Logger.info(String.format("发送请求 %s on %s%n%s",request.url(),chain.connection(),request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();//收到响应的时间
//不能直接使用response.body().string()的方式输出日志
//因为response.body().string()之后,response中的流会被关闭,程序会报错,
// 我们需要创建出一个新的response给应用层处理
ResponseBody responseBody = response.peekBody(1024 * 1024);
Logger.info(String.format("接收响应:[%s] %n返回json:%s %.1fms%n%s",
response.request().url(),
responseBody.string(),
(t2-t1) /1e6d,
response.headers()
));
return response;
}
}
- 请求时我们用了两种方法,我们先看第一种使用O看Http的;
private void useOkHttp() {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
Request request = new Request.Builder().url(Urls.requestJokesUrl)
.header("User-Agent", "OkHttp Example")
.build();
client.newCall(request).enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
}
@Override
public void onResponse(okhttp3.Call call, Response response) throws IOException {
runOnUiThread(new
Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "请求成功", Toast.LENGTH_SHORT).show();
}
});
}
});
}
- 接下来我们看第二种使用Retrofit的;
用到的接口JokesRequest_interface.java
public interface JokesRequest_interface {
@Headers("User-Agent:OkHttp Example")
@GET("content/text.php")
Call<JokesBean> getJokes(@Query("key") String key,@Query("page") String page,@Query("pagesize") String pageSize);
}
开始请求:
private void useRetrofit() {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Urls.baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
JokesRequest_interface request = retrofit.create(JokesRequest_interface.class);
Call<JokesBean> call = request.getJokes(Constant.DOUBIAN_KEY, "1", "1");
call.enqueue(new Callback<JokesBean>() {
@Override
public void onResponse(Call<JokesBean> call, retrofit2.Response<JokesBean> response) {
Toast.makeText(MainActivity.this, "请求成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<JokesBean> call, Throwable t) {
}
});
}
-
最后我们看看拦截到的log日志
我测试的接口是申请的聚合的笑话大全