java - 如何在 Java 中访问 HTTP 响应对象的值
问题描述
我正在向服务器发送请求并获得对 Response 对象的响应。它在邮递员中输出一个 Json 对象。我需要知道访问其中值的方法。这是我的代码。
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
if(response.code() == 200) {
//need to access the response object
} catch (JSONException e) {
e.printStackTrace();
}
}
}
这是邮递员针对同一请求的输出
[
{
"id": 1,
"name": "a"
},
{
"id": 2,
"name": "Udana"
},
]
当我这样尝试 JSONObject jsonObject = new JSONObject(response.toString());
它给出了以下错误
W/System.err:org.json.JSONException:java.lang.String 类型的值响应无法转换为 JSONObject
解决方案
您可以指定Call
和Response
键入。例如,代表 JSON 对象的 beanCall<List<IdNameType>>
在哪里。IdNameType
以下草稿:
public void onResponse(Call<List<IdNameType>> call, Response<List<IdNameType>> response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
if(response.code() == 200) {
List<IdNameType> responseContent = response.body();
// Use response
} catch (JSONException e) {
e.printStackTrace();
}
}
}
否则,您可以手动管理获取原始 OkHttp 响应的响应内容Response::raw
。
推荐阅读
- php - 将不同的类添加到标签和值并在同一行输出
- c# - NUnit 如何将屏幕截图附加到 Azure Pipeline 中的测试附件
- python - 当x轴的数量不连续时,Python Matlibplot条形图之间的空间
- java - 为亚马逊 s3 上的每个视频商店创建缩略图的最佳方法是什么?
- jenkins - 一个关于Jenkins中“单体”项目的CI流程的问题
- php - 在codeigniter中两次上传相同的文件
- javascript - 气泡图:无法读取未定义的属性“parts/Globals.js”
- objective-c - 如何使用objective-c向接口公开自定义初始化实现?
- java - Headless chrome 删除输入值 - 日期时间字段
- python - Tkinter 获取坐标的平均值