簡體   English   中英

改造正在返回一個空的響應正文

[英]Retrofit is returning an empty response body

我正在嘗試使用改造和 gson 來解析一些 JSON。 但是,我得到一個空的響應體。 當我嘗試從對象打印信息時,我收到 NullPointerException。

我已確保 URL 正確,並且我確信我的 POJO 也是正確的。 我正在使用 jsonschema2pojo 來幫助創建 POJO 類。

這是我試圖解析的 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": ""
}

}

這是我的改造客戶端/設置

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

最后,這是我的 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());

這是回應。 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

這很可能是您的 POJO 課程。 我剛遇到這個問題。

嘗試創建一個只包含根及其 id 的類。 目前。

class TrainArrival {

    public TrainArrival() {
    }

    @SerializedName("root")
    Root root;

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

我剛剛注意到,您的getData()返回值與您的response不匹配。 我很驚訝它甚至編譯。

它應該是

public interface ApiInterface {

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

如果這不起作用,那么您需要通過創建自己的 OkHttpClient 來攔截原始響應以查看問題是否在那里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM