Retrofit callback get response body

前端 未结 9 1121
星月不相逢
星月不相逢 2020-12-05 04:05

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:

RestAdapter          


        
相关标签:
9条回答
  • 2020-12-05 04:38

    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

    0 讨论(0)
  • 2020-12-05 04:41

    Inside callback's angle brackets write "Response" and then extract the stream from this 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) {
    
        }
    });
    
    0 讨论(0)
  • 2020-12-05 04:44

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

    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

    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;
    }
    
    0 讨论(0)
  • 2020-12-05 04:47

    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.

    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"

    My Pojo would look like this:

    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.

    0 讨论(0)
  • 2020-12-05 04:49

    Before Retrofit 2.0

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

    Retrofit 2.0

     String  bodyString = new String(response.body().bytes());
    
    0 讨论(0)
  • 2020-12-05 04:50

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

    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.FULL in the setLogLevel method, if not then it won't parse the InputStream from response.getBody().in() as it's already been read and closed.

    0 讨论(0)
提交回复
热议问题