【发布时间】:2020-12-26 22:19:37
【问题描述】:
我正在尝试使用对 API 的 GET 请求来获取一些日期。我想要做的是将此请求的响应保存为我事先创建的 Java 类。这是我的课:
import java.util.List;
public class Person {
String name = null;
List<Siblings> siblings = null;
}
以下是我发送 GET 请求并以字符串形式读取数据的方式:
try {
URL url = new URL("someURL");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Bearer " + "bearerString");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
InputStream content = (InputStream) connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
如何将 Http 请求的响应保存在一个类对象中,而不仅仅是一个字符串?
【问题讨论】:
-
这取决于:响应格式是什么? XML? JSON?带有序列化Java对象的字节? CSV 文本?还有什么?
-
这是 JSON,@Andreas
-
然后使用同样支持对象映射的 JSON parser 库,例如杰克逊,格森,...
-
这回答了你的问题:How to parse JSON in Java
标签: java get-request