Android 改造回调获取响应体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22325641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:50:08  来源:igfitidea点击:

Retrofit callback get response body

androidretrofit

提问by Kerwan

I am testing Retrofit to compare it with Volley and I am struggling to get the response from my requests. For example, I do something like this:

我正在测试 Retrofit 以将其与 Volley 进行比较,但我正在努力从我的请求中获得响应。例如,我做这样的事情:

RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint("http://localhost:8080")
            .build();

MyService service = restAdapter.create(MyService.class);
service.getToto("toto", new Callback<Toto>() {

        @Override
        public void success(Toto toto, Response response) {
            // Try to get response body
            BufferedReader reader = null;
            StringBuilder sb = new StringBuilder();
            try {
                reader = new BufferedReader(
                    new InputStreamReader(response.getBody().in()));
                String line;
                try {
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            String result = sb.toString();
        }

        @Override
        public void failure(RetrofitError error) {}
    });

It works, the object totois set, but for testing purposes, I also want to display the JSON response returned by the server.

它有效,对象toto已设置,但出于测试目的,我还想显示服务器返回的 JSON 响应。

So I am trying to read the InputStreamfrom response.getBody()which is a TypedInputStream. Unfortunately, I always get an IOException : Stream is closed.

所以我试图InputStreamresponse.getBody()其中读取TypedInputStream. 不幸的是,我总是得到一个IOException : Stream is closed.

I tried to use the Utilsclass from Retrofit but I get the same IOExceptionerror.

我尝试使用Retrofit 中的Utils类,但出现相同的IOException错误。

回答by Nitesh Kumar

Inside callback's angle brackets write "Response" and then extract the stream from this response.

在回调的尖括号内写入“Response”,然后从此响应中提取流。

service.getToto("toto", new Callback<Response>() {
    @Override
    public void success(Response result, Response response) {

        //Try to get response body
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();
        try {

            reader = new BufferedReader(new InputStreamReader(result.getBody().in()));

            String line;

            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        String result = sb.toString();
    }

    @Override
    public void failure(RetrofitError error) {

    }
});

回答by shiami

Before Retrofit 2.0

改造 2.0 之前

   String bodyString = new String(((TypedByteArray) response.getBody()).getBytes());

Retrofit 2.0

改造 2.0

 String  bodyString = new String(response.body().bytes());

回答by droppin_science

If you set .setLogLevel(RestAdapter.LogLevel.FULL)on the RestAdapterthat you use to create the service you should get the raw JSON response output in the debug console.

如果您设置.setLogLevel(RestAdapter.LogLevel.FULL)RestAdapter用于创建服务的 ,则应该在调试控制台中获得原始 JSON 响应输出。

RestAdapter restAdapter = new RestAdapter.Builder()
    .setServer("http://my_lovely_api.com")
    .setLogLevel(RestAdapter.LogLevel.FULL)
    .build();

mService = restAdapter.create(MyService.class);

If you want to do something different with this raw response you can still use the code you have in your success block to create a JSON string assuming that you keep the LogLevel.FULLin the setLogLevelmethod, if not then it won't parse the InputStream from response.getBody().in()as it's already been read and closed.

如果你想对这个原始响应做一些不同的事情,你仍然可以使用你在成功块中的代码来创建一个 JSON 字符串,假设你保留LogLevel.FULLsetLogLevel方法中,如果没有,那么它不会解析 InputStream ,response.getBody().in()因为它是已经阅读并关闭。

回答by Michael Alan Huff

I recently encountered a similar problem. I wanted to look at some json in the response body but didn't want to deal with the TypedByteArray from Retrofit. I found the quickest way to get around it was to make a Pojo(Plain Old Java Object) with a single String field. More Generally you would make a Pojo with one field corresponding to whatever data you wanted to look at.

我最近遇到了类似的问题。我想查看响应正文中的一些 json,但不想处理来自 Retrofit 的 TypedByteArray。我发现解决它的最快方法是使用单个 String 字段创建一个 Pojo(Plain Old Java Object)。更一般地,您会制作一个 Pojo,其中一个字段对应于您想要查看的任何数据。

For example, say I was making a request in which the response from the server was a single string in the response's body called "access_token"

例如,假设我发出一个请求,其中来自服务器的响应是响应正文中名为“access_token”的单个字符串

My Pojo would look like this:

我的 Pojo 看起来像这样:

public class AccessToken{
    String accessToken;

    public AccessToken() {}

    public String getAccessToken() {
        return accessToken;
    }
} 

and then my callback would look like this

然后我的回调看起来像这样

Callback<AccessToken> callback = new Callback<AccessToken>() {
   @Override
   public void success(AccessToken accessToken, Response response) {
       Log.d(TAG,"access token: "+ accessToken.getAccessToken());
   }

   @Override
   public void failure(RetrofitError error) {
       Log.E(TAG,"error: "+ error.toString());
   }
};

This will enable you to look at what you received in the response.

这将使您能够查看您在响应中收到的内容。

回答by Kirill Vashilo

Please, don't use streams and straemReaders for this. Use smart solutions like square does:

请不要为此使用流和 straemReaders。使用像 square 那样的智能解决方案:

private Response logAndReplaceResponse(String url, Response response, long elapsedTime)

http://www.programcreek.com/java-api-examples/index.php?source_dir=retrofit-jaxrs-master/retrofit/src/main/java/retrofit/RestAdapter.java

http://www.programcreek.com/java-api-examples/index.php?source_dir=retrofit-jaxrs-master/retrofit/src/main/java/retrofit/RestAdapter.java

example:

例子:

private String getResponseBody(Response response) {
    String result = "";
    //Try to get response body
    if (response.getBody() instanceof TypedByteArray) {
        TypedByteArray b = (TypedByteArray) response.getBody();
        result = new String(b.getBytes());
    }
    return result;
}

回答by Ravi Selvaraj

With version 2.1.0, you can get the content as

使用 2.1.0 版,您可以获取内容为

public void onResponse(Call<T> call, Response<T> response) {
    String errorString = response.errorBody().string();
}

回答by loeschg

Another solution would be to do something like the following:

另一种解决方案是执行以下操作:

  private static String bodyAsString(RequestBody body) {
    try {
      Buffer buffer = new Buffer();
      body.writeTo(buffer);
      return buffer.readString(body.contentType().charset());
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

Taken from https://github.com/square/okhttp/blob/master/okcurl/src/test/java/com/squareup/okhttp/curl/MainTest.java#L93-L101

摘自https://github.com/square/okhttp/blob/master/okcurl/src/test/java/com/squareup/okhttp/curl/MainTest.java#L93-L101

回答by Nishanth S Babu

Just do it like this:

只需这样做:

ModelClass modelclass=response.response.body()
System.out.println("****************-----retro rsp----1-------"+modelclass.getMessage());

回答by Osvaldo Bringaz

in your model of response press cmd+n and override "toString" method and only call as response.toString();

在您的响应模型中,按 cmd+n 并覆盖“toString”方法并仅调用 response.toString();

@Override
public String toString() {
    return "{" +
            "key_one='" + var_keyone + '\'' +
            ", key_two='" + var_keytwo + '\'' +
            '}';
}