Retrofit callback get response body

前端 未结 9 1120
星月不相逢
星月不相逢 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: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 callback = new Callback() {
       @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.

提交回复
热议问题