从 Java 中的 Curl Post 请求获取 Json / 响应正文
Get Json / Resonse body from Curl Post Request in Java
这是我编写的发送 POST 请求发送电子邮件的方法。
我能够发送电子邮件并获得响应代码 200 Ok。
但我不知道如何获取 JSON 响应并将其转换为对象。
有人可以告诉我该怎么做吗?
public void sendEmail() {
try {
URL url = new URL("https://mandrillapp.com/api/1.0/messages/send");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
String data =
"{\"key\": \"" + mailchimpApiKey + "\", " +
"\"message\": {" +
"\"from_email\": \"from@gmail.com\", " +
"\"subject\": \"Hello World\", " +
"\"text\": \"Welcome to Mailchimp Transactional!\", " +
"\"to\": [{ \"email\": \"to@gmail.com\", \"type\": \"to\" }]}}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = httpURLConnection.getOutputStream();
stream.write(out);
System.out.println(httpURLConnection.getResponseCode() + " " + httpURLConnection.getResponseMessage());
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
基本搜索显示:https://www.baeldung.com/httpurlconnection-post#8-read-the-response-from-input-stream
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
如果响应采用 JSON 格式,请使用任何 third-party JSON 解析器,例如 Jackson 库、Gson 或 org.json 来解析响应。
您可以根据收到的 response code
得到 errorStream
或 inputStream
并从中得到响应。下面的示例从流
创建一个 BufferedReader
BufferedReader br = null;
if (100 <= httpURLConnection.getResponseCode() && httpURLConnection.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
}
然后您可以根据需要从 br
中读取和存储数据。下面将数据存入StringBuilder
StringBuilder data = new StringBuilder();
String dataLine = null;
while ((dataLine = br.readLine()) != null) {
data.append(dataLine.trim());
}
System.out.println(data.toString());
除了打印为 String
,您还可以使用 JSON
库将其转换为 JSON
。您可以关注 this guide
除了@mdre的回答
我使用 org.json 库将响应转换为 JSON 对象。以下方法正是这样做的:
import org.json.JSONException;
import org.json.JSONObject;
public static JSONObject convertResponseToJSONObject(String responseString) {
try {
JSONObject jsonObj = new JSONObject(responseString);
return jsonObj;
} catch (JSONException e) {
System.err.println(
"It is not possible to create a JSONObject from the input string, returning null. Exception:");
e.printStackTrace();
}
return null;
}
请注意,如果响应以 {
开头,则响应仅表示 JSON 对象。如果它以 [
开头,则响应表示一个 JSON 数组。
这是我编写的发送 POST 请求发送电子邮件的方法。 我能够发送电子邮件并获得响应代码 200 Ok。 但我不知道如何获取 JSON 响应并将其转换为对象。 有人可以告诉我该怎么做吗?
public void sendEmail() {
try {
URL url = new URL("https://mandrillapp.com/api/1.0/messages/send");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
String data =
"{\"key\": \"" + mailchimpApiKey + "\", " +
"\"message\": {" +
"\"from_email\": \"from@gmail.com\", " +
"\"subject\": \"Hello World\", " +
"\"text\": \"Welcome to Mailchimp Transactional!\", " +
"\"to\": [{ \"email\": \"to@gmail.com\", \"type\": \"to\" }]}}";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = httpURLConnection.getOutputStream();
stream.write(out);
System.out.println(httpURLConnection.getResponseCode() + " " + httpURLConnection.getResponseMessage());
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
基本搜索显示:https://www.baeldung.com/httpurlconnection-post#8-read-the-response-from-input-stream
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
如果响应采用 JSON 格式,请使用任何 third-party JSON 解析器,例如 Jackson 库、Gson 或 org.json 来解析响应。
您可以根据收到的 response code
得到 errorStream
或 inputStream
并从中得到响应。下面的示例从流
BufferedReader
BufferedReader br = null;
if (100 <= httpURLConnection.getResponseCode() && httpURLConnection.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
}
然后您可以根据需要从 br
中读取和存储数据。下面将数据存入StringBuilder
StringBuilder data = new StringBuilder();
String dataLine = null;
while ((dataLine = br.readLine()) != null) {
data.append(dataLine.trim());
}
System.out.println(data.toString());
除了打印为 String
,您还可以使用 JSON
库将其转换为 JSON
。您可以关注 this guide
除了@mdre的回答
我使用 org.json 库将响应转换为 JSON 对象。以下方法正是这样做的:
import org.json.JSONException;
import org.json.JSONObject;
public static JSONObject convertResponseToJSONObject(String responseString) {
try {
JSONObject jsonObj = new JSONObject(responseString);
return jsonObj;
} catch (JSONException e) {
System.err.println(
"It is not possible to create a JSONObject from the input string, returning null. Exception:");
e.printStackTrace();
}
return null;
}
请注意,如果响应以 {
开头,则响应仅表示 JSON 对象。如果它以 [
开头,则响应表示一个 JSON 数组。