简体   繁体   English

改造正在返回一个空的响应正文

[英]Retrofit is returning an empty response body

I'm trying to use retrofit & gson to parse some JSON.我正在尝试使用改造和 gson 来解析一些 JSON。 However, I am getting an empty response body.但是,我得到一个空的响应体。 When I try to print information from an object I get a NullPointerException.当我尝试从对象打印信息时,我收到 NullPointerException。

I have made sure that the URL is correct and I'm sure my POJOs are correct as well.我已确保 URL 正确,并且我确信我的 POJO 也是正确的。 I am using jsonschema2pojo to help create the POJO classes.我正在使用 jsonschema2pojo 来帮助创建 POJO 类。

Here is the JSON I'm trying to parse这是我试图解析的 JSON

{
"?xml": {
    "@version": "1.0",
    "@encoding": "utf-8"
},
"root": {
    "@id": "1",
    "uri": {
        "#cdata-section": "http://api.bart.gov/api/etd.aspx?cmd=etd&orig=ANTC&json=y"
    },
    "date": "05/07/2019",
    "time": "02:00:01 PM PDT",
    "station": [
        {
            "name": "Antioch",
            "abbr": "ANTC",
            "etd": [
                {
                    "destination": "SFO/Millbrae",
                    "abbreviation": "MLBR",
                    "limited": "0",
                    "estimate": [
                        {
                            "minutes": "10",
                            "platform": "2",
                            "direction": "North",
                            "length": "1",
                            "color": "YELLOW",
                            "hexcolor": "#ffff33",
                            "bikeflag": "1",
                            "delay": "0"
                        },
                        {
                            "minutes": "25",
                            "platform": "2",
                            "direction": "North",
                            "length": "1",
                            "color": "YELLOW",
                            "hexcolor": "#ffff33",
                            "bikeflag": "1",
                            "delay": "0"
                        },
                        {
                            "minutes": "40",
                            "platform": "2",
                            "direction": "North",
                            "length": "1",
                            "color": "YELLOW",
                            "hexcolor": "#ffff33",
                            "bikeflag": "1",
                            "delay": "0"
                        }
                    ]
                }
            ]
        }
    ],
    "message": ""
}

} }

This is my retrofit client / setup这是我的改造客户端/设置

public class RetrofitClient {

private static Retrofit sRetrofit = null;

public static Retrofit getClient(String baseUrl) {
    if (sRetrofit == null) {
        sRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return sRetrofit;
}

public interface ApiInterface {

    // public API key
    @GET("api/etd.aspx?cmd=etd&key=MW9S-E7SL-26DU-VV8V&orig=ANTC&json=y")
    Call<Root> getData();
}

public class ApiUtils {

    public static final String BASE_URL = "http://api.bart.gov/";

    public static ApiInterface getApiInterface() {
    return RetrofitClient.getClient(BASE_URL).create(ApiInterface.class);
}

Finally, this is the code in my onCreateView最后,这是我的 onCreateView 中的代码

    mService = ApiUtils.getApiInterface();
    mService.getData().enqueue(new Callback<TrainArrival>() {
        @Override
        public void onResponse(Call<TrainArrival> call, Response<TrainArrival> response) {
            if (response.isSuccessful()) {
                trainData = response.body();
                Log.d("TAG", new GsonBuilder().setPrettyPrinting().create().toJson(response));
            } else {
                int statusCode = response.code();
                Log.d("TAG", Integer.toString(statusCode));
            }
        }

        @Override
        public void onFailure(Call<TrainArrival> call, Throwable t) {
            Log.d("TAG", t.getMessage());
        }
    });
    Log.d("TAG", trainData.getDate());

This is the response.这是回应。 The body tag is empty. body 标签是空的。

{
  "body": {},
  "rawResponse": {
    "body": {
      "contentLength": 731,
      "contentType": {
        "charset": "utf-8",
        "mediaType": "application/json; charset\u003dutf-8",
        "subtype": "json",
        "type": "application"
      }
    },
    "code": 200,
    "headers": {
      "namesAndValues": [
        "Cache-Control",
        "no-cache",
        "Pragma",
        "no-cache",
        "Content-Type",
        "application/json; charset\u003dutf-8",
        "Expires",
        "-1",
        "Server",
        "Microsoft-IIS/8.5",
        "Access-Control-Allow-Origin",
        "*",
        "X-AspNet-Version",
        "4.0.30319",
        "X-Powered-By",
        "ASP.NET",
        "Date",
        "Wed, 08 May 2019 00:02:00 GMT",
        "Content-Length",
        "731"
      ]
    },
    "message": "OK",
    "networkResponse": {
      "code": 200,
      "headers": {
        "namesAndValues": [
          "Cache-Control",
          "no-cache",
          "Pragma",
          "no-cache",
          "Content-Type",
          "application/json; charset\u003dutf-8",
          "Expires",
          "-1",
          "Server",
          "Microsoft-IIS/8.5",
          "Access-Control-Allow-Origin",
          "*",
          "X-AspNet-Version",
          "4.0.30319",
          "X-Powered-By",
          "ASP.NET",
          "Date",
          "Wed, 08 May 2019 00:02:00 GMT",
          "Content-Length",
          "731"
        ]
      },
      "message": "OK",
      "protocol": "HTTP_1_1",
      "receivedResponseAtMillis": 1557273722035,
      "request": {
        "cacheControl": {
          "immutable": false,
          "isPrivate": false,
          "isPublic": false,
          "maxAgeSeconds": -1,
          "maxStaleSeconds": -1,
          "minFreshSeconds": -1,
          "mustRevalidate": false,
          "noCache": false,
          "noStore": false,
          "noTransform": false,
          "onlyIfCached": false,
          "sMaxAgeSeconds": -1
        },
        "headers": {
          "namesAndValues": [
            "Host",
            "api.bart.gov",
            "Connection",
            "Keep-Alive",
            "Accept-Encoding",
            "gzip",
            "User-Agent",
            "okhttp/3.12.0"
          ]
        },
        "method": "GET",
        "tags": {
          "class retrofit2.Invocation": {
            "arguments": [],
            "method": {
              "artMethod": 502253502104,
              "override": false
            }
          }
        },
        "url": {
          "host": "api.bart.gov",
          "password": "",
          "pathSegments": [
            "api",
            "etd.aspx"
          ],
          "port": 80,
          "queryNamesAndValues": [
            "cmd",
            "etd",
            "key",
            "MW9S-E7SL-26DU-VV8V",
            "orig",
            "ANTC",
            "json",
            "y"
          ],
          "scheme": "http",
          "url": "http://api.bart.gov/api/etd.aspx?cmd\u003detd\u0026key\u003dMW9S-E7SL-26DU-VV8V\u0026orig\u003dANTC\u0026json\u003dy",
          "username": ""
        }
      },
      "sentRequestAtMillis": 1557273721989
    },
    "protocol": "HTTP_1_1",
    "receivedResponseAtMillis": 1557273722035,
    "request": {
      "headers": {
        "namesAndValues": []
      },
      "method": "GET",
      "tags": {
        "class retrofit2.Invocation": {
          "arguments": [],
          "method": {
            "artMethod": 502253502104,
            "override": false
          }
        }
      },
      "url": {
        "host": "api.bart.gov",
        "password": "",
        "pathSegments": [
          "api",
          "etd.aspx"
        ],
        "port": 80,
        "queryNamesAndValues": [
          "cmd",
          "etd",
          "key",
          "MW9S-E7SL-26DU-VV8V",
          "orig",
          "ANTC",
          "json",
          "y"
        ],
        "scheme": "http",
        "url": "http://api.bart.gov/api/etd.aspx?cmd\u003detd\u0026key\u003dMW9S-E7SL-26DU-VV8V\u0026orig\u003dANTC\u0026js

It's most likely your POJO class.这很可能是您的 POJO 课程。 I just had this problem.我刚遇到这个问题。

Try to create a class that only contains the root and its id.尝试创建一个只包含根及其 id 的类。 For now.目前。

class TrainArrival {

    public TrainArrival() {
    }

    @SerializedName("root")
    Root root;

    class Root {
        @SerializedName("@id")
        public int id;
    }
}

I just noticed, your getData() return value does not match your response .我刚刚注意到,您的getData()返回值与您的response不匹配。 I'm surprised it even compiled.我很惊讶它甚至编译。

It should be它应该是

public interface ApiInterface {

    // public API key
    @GET("api/etd.aspx?cmd=etd&key=MW9S-E7SL-26DU-VV8V&orig=ANTC&json=y")
    Call<TrainArrival> getData();
}

If this doesn't work, then you need to intercept the raw response to see if the problem is in there by creating your own OkHttpClient.如果这不起作用,那么您需要通过创建自己的 OkHttpClient 来拦截原始响应以查看问题是否在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM