Retrofit @GET - 如何显示请求字符串?

26

我正在开发一个使用Retrofit创建RESTful客户端的Android应用程序。为了调试网络调用,我想要显示或转储实际被调用的URL。有没有办法做到这一点?下面包含了一些代码,展示了目前应用程序如何使用Retrofit。

客户端接口定义:

import retrofit.Callback;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.Headers;
import retrofit.http.POST;
import retrofit.http.Path;

// etc...

 public interface MyApiClient {

    @Headers({
            "Connection: close"
    })

    @GET("/{userId}/{itemId}/getCost.do")
    public void get(@Path("userId") String userId, @Path("itemId") String userId, Callback<Score> callback);


//....etc 

}

使用生成的客户端的服务:

// etc...
    import javax.inject.Inject;
    import retrofit.Callback;
    import retrofit.RetrofitError;
    import retrofit.client.Response;


@Inject
MyApiClient myApiClient;

// etc...
               myApiClient.getCost(myId, itemId, new Callback<Cost>() {
                     @Override
                    public void success(Cost cost, Response response) {
                        Log.d("Success: %s", String.valueOf(cost.cost));
                        if (cost.cost != -1) {
                            processFoundCost(cost);
                        } else {
                            processMissingCost(itemId);
                        }
                        stopTask();
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        handleFailure(new CostFailedEvent(), null);
                    }
                });
            }
3个回答

57
< p > call.request().url() 是基于retrofit2.Call类型的调用。


10

RetrofitError有一个getUrl()方法,返回URL。

此外,在回调中,Response也有一个getUrl()方法。

另外,您还可以根据这个问题指定日志级别:

RestAdapter adapter = (new RestAdapter.Builder()).
//...
           setLogLevel(LogLevel.FULL).setLog(new AndroidLog("YOUR_LOG_TAG"))              

尽管根据文档,LogLevel.BASIC应该满足您的需求,但请注意:docs
BASIC
Log only the request method and URL and the response status code and execution time.

6

是的,你可以通过在 RestAdapter 上调用 setLogLevel() 方法启用调试日志记录。

我通常会将日志记录设置为像这样的 LogLevel.FULL 以供调试构建使用:

RestAdapter adapter = builder.setEndpoint("example.com")
    .setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)
    .build();

这将自动打印出与您的HTTP请求相关的所有信息,包括您正在访问的URL、头文件以及请求和响应的正文。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接