【问题标题】:Retrofit @GET - how to display request string?改造@GET - 如何显示请求字符串?
【发布时间】:2015-07-17 03:47:03
【问题描述】:

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

客户端接口定义:

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);
                    }
                });
            }

【问题讨论】:

    标签: java android retrofit


    【解决方案1】:

    call.request().url(),其中callretrofit2.Call 的类型。

    【讨论】:

      【解决方案2】:

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

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

      那个,你也可以按照this question指定日志级别:

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

      虽然基于docsLogLevel.BASIC 应该可以满足您的需求。

      BASIC
      Log only the request method and URL and the response status code and execution time.
      

      【讨论】:

        【解决方案3】:

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

        我通常将日志记录设置为 LogLevel.FULL 以进行调试构建,如下所示:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-01-13
          • 2016-06-16
          • 1970-01-01
          • 2015-10-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多