无法通过twitter api获得改装拦截器

时间:2018-01-25 07:51:01

标签: android rest retrofit

此代码段来自名为tweetz的github repo:

public class RetrofitInterceptor implements Interceptor {

private String token = null;

@Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    if (token == null) {
        ResponseBody body = chain.proceed(getToken()).body();

        try {
            JSONObject jsonObject = new JSONObject(body.string());
            token = "Bearer " + jsonObject.optString("access_token");
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d(RetrofitInterceptor.class.getName(), "Error fetching token");
        }
    }

    request = request.newBuilder()
            .addHeader("Authorization", token)
            .build();

    return chain.proceed(request);
}

private Request getToken() {
    String bearerToken = BuildConfig.CONSUMER_KEY +
            ":" + BuildConfig.CONSUMER_SECRET;

    String base64BearerToken = "Basic " + Base64.encodeToString(bearerToken.getBytes(), Base64.NO_WRAP);
    RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8"), "grant_type=client_credentials");

    return new Request.Builder()
            .url(BuildConfig.AUTH_END_POINT)
            .post(requestBody)
            .header("Authorization", base64BearerToken)
            .header("Content-Encoding", "gzip")
            .header("User-Agent", "My Twitter App v1.0.23")
            .header("Content-type", "application/x-www-form-urlencoded;charset=UTF-8")
            .build();
}

}

当我运行应用程序时,以下行会导致json异常

 JSONObject jsonObject = new JSONObject(body.string());

这里是logcat输出:

01-29 06:24:44.923 2837-2906/com.rahulrv.tweetz W/System.err: org.json.JSONException: End of input at character 0 of 
01-29 06:24:44.923 2837-2906/com.rahulrv.tweetz W/System.err:     at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
01-29 06:24:44.923 2837-2906/com.rahulrv.tweetz W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
01-29 06:24:44.923 2837-2906/com.rahulrv.tweetz W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:156)
01-29 06:24:44.923 2837-2906/com.rahulrv.tweetz W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
01-29 06:24:44.923 2837-2906/com.rahulrv.tweetz W/System.err:     at com.rahulrv.tweetz.api.RetrofitInterceptor.intercept(RetrofitInterceptor.java:39)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:190)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at okhttp3.RealCall.execute(RealCall.java:57)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at com.jakewharton.retrofit2.adapter.rxjava2.CallObservable.subscribeActual(CallObservable.java:41)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at io.reactivex.Observable.subscribe(Observable.java:10514)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at com.jakewharton.retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at io.reactivex.Observable.subscribe(Observable.java:10514)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at io.reactivex.internal.operators.observable.ObservableSubscribeOn$1.run(ObservableSubscribeOn.java:39)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz W/System.err:     at java.lang.Thread.run(Thread.java:761)
01-29 06:24:44.924 2837-2906/com.rahulrv.tweetz D/com.rahulrv.tweetz.api.RetrofitInterceptor: Error fetching token

我知道问题的根源,但我不知道如何解决它。是由于null ResponseBody对象,这意味着我们更新令牌并创建新请求后,新请求不会更新,但为什么会这样?我不知道?

1 个答案:

答案 0 :(得分:0)

使用HttpLoggingInterceptor和OkHttpClient查看有关请求和响应的所有信息。问题可能是body.string()为空或null。

https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor

compile 'com.squareup.retrofit2:converter-scalars:2.2.0'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0'

还要检查Retrofit 2中的响应状态

@Override
public void onResponse(Call<YourModel> call, Response<YourModel> response) {
    if (response.code() == 200) {
       // Do awesome stuff
    } else {
       // Handle other response codes
    }
}

响应可能是200(成功响应)而不是等待正文(正文为空或空)。