如何访问 RapidApi 城市词典 Android 响应正文中的数据

Posted

技术标签:

【中文标题】如何访问 RapidApi 城市词典 Android 响应正文中的数据【英文标题】:How to access data in response body for RapidApi urban dictionary Android 【发布时间】:2020-04-13 11:20:24 【问题描述】:

我收到响应正文 ** 是 okhttp3.internal.http.RealResponseBody@6e33b4c 如何将其转换为 json 或字符串。

OkHttpClient client = new OkHttpClient();
           Request request = new Request.Builder()
                   .url("https://mashape-community-urban-dictionary.p.rapidapi.com/define?term=check")
                   .get()
                   .addHeader("x-rapidapi-host", "mashape-community-urban-dictionary.p.rapidapi.com")
                   .addHeader("x-rapidapi-key", API)
                   .build();

           Response response = client.newCall(request).execute();

           Log.d("TAG", "response:toString() " + response.toString());
           Log.d("TAG", "response:headers " + response.headers());
           Log.d("TAG", "response:body " + response.body());
           Log.d("TAG", "response:challenges " + response.challenges());
           Log.d("TAG", "response:message " + response.message());

日志

response:toString() Responseprotocol=http/1.1, code=200, message=OK, url=https://mashape-community-urban-dictionary.p.rapidapi.com/define?term=check

response:headers Cache-Control: no-cache, no-store, must-revalidate
Content-Type: application/json; charset=utf-8
Date: Mon, 13 Apr 2020 11:03:35 GMT
Server: RapidAPI-1.1.0
Via: 1.1 google
X-License: http://api.urbandictionary.com/
X-RapidAPI-Region: AWS - ap-southeast-1
X-RapidAPI-Version: 1.1.0
Content-Length: 4386
Connection: keep-alive

response:body okhttp3.internal.http.RealResponseBody@6e33b4c

response:challenges []

response:message OK

在 RAPID API DEVELOPER DASHBOARD 中,我可以看到响应体如何将其转换为字符串或 JSON?

【问题讨论】:

你考虑过使用 Retrofit 吗?它会让你的生活更轻松。 【参考方案1】:

这会得到 JSON 格式的列表

  JSONObject object = new JSONObject(response.body().string());

  final JSONArray array = object.getJSONArray("list");

【讨论】:

以上是关于如何访问 RapidApi 城市词典 Android 响应正文中的数据的主要内容,如果未能解决你的问题,请参考以下文章

尝试在 Android Studio 上实现 RapidApi

缺少 RapidAPI 应用程序密钥(不缺少)

RapidApi 安卓

如何保护 Android apk 包中的 rapidapi 密钥

如何在 VBA Excel 中使用 RapidAPI(WhoIs 域名)

如何在 laravel Controller 中获取 Rapidapi?