[英]Get Json / Resonse body from Curl Post Request in Java
This is the method I have written which sends a POST request to send an Email.这是我编写的发送 POST 请求以发送电子邮件的方法。 I am able to send the email and get the Response Code 200 Ok.
我能够发送电子邮件并获得响应代码 200 Ok。 But I don't know how to get the JSON Response and convert it into an Object.
但我不知道如何获取 JSON 响应并将其转换为对象。 Can someone please tell me how to do this?
有人可以告诉我该怎么做吗?
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();
}
}
A basic search reveals: https://www.baeldung.com/httpurlconnection-post#8-read-the-response-from-input-stream基本搜索显示: 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());
}
If the response is in JSON format, use any third-party JSON parsers such as Jackson library, Gson, or org.json to parse the response.如果响应是 JSON 格式,请使用任何第三方 JSON 解析器,例如 Jackson 库、Gson 或 org.json 来解析响应。
In addition to the answer by @mdre除了@mdre 的回答
I use the org.json library to convert responses into JSON Objects.我使用org.json库将响应转换为 JSON 对象。 The following method does exactly this:
以下方法正是这样做的:
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;
}
Note that the response only represents a JSON object if it starts with a {
.请注意,响应仅表示以
{
开头的 JSON 对象。 If it starts with a [
the response represents a JSON array.如果它以
[
开头,则响应表示 JSON 数组。
You can get errorStream
or inputStream
based on the response code
you receive and get the response from it.您可以根据收到的
response code
获取errorStream
或inputStream
并从中获取响应。 Below example creates a BufferedReader
from the stream下面的示例从流中创建一个
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()));
}
You can then read from the br
and store data based on your requirement.然后,您可以根据您的要求从
br
中读取并存储数据。 Below will store data into StringBuilder
下面将数据存储到
StringBuilder
StringBuilder data = new StringBuilder();
String dataLine = null;
while ((dataLine = br.readLine()) != null) {
data.append(dataLine.trim());
}
System.out.println(data.toString());
Instead of printing as String
you can also convert it into JSON
by using JSON
libraries.除了作为
String
打印,您还可以使用JSON
库将其转换为JSON
。 You may follow this guide您可以按照本指南
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.