- 首先我們需要在項(xiàng)目中添加依賴
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
- 創(chuàng)建攔截器
public class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
//Chain 里包含了request和response
Request request = chain.request();
long t1 = System.nanoTime();//請求發(fā)起的時間
Logger.info(String.format("發(fā)送請求 %s on %s%n%s",request.url(),chain.connection(),request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();//收到響應(yīng)的時間
//不能直接使用response.body().string()的方式輸出日志
//因?yàn)閞esponse.body().string()之后涨共,response中的流會被關(guān)閉越败,程序會報(bào)錯,
// 我們需要創(chuàng)建出一個新的response給應(yīng)用層處理
ResponseBody responseBody = response.peekBody(1024 * 1024);
Logger.info(String.format("接收響應(yīng):[%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日志
log
我測試的接口是申請的聚合的笑話大全