这是我编写的发送 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\": \"[email protected]\", " +
"\"subject\": \"Hello World\", " +
"\"text\": \"Welcome to Mailchimp Transactional!\", " +
"\"to\": [{ \"email\": \"[email protected]\", \"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 格式,请使用任何第三方 JSON 解析器,例如 Jackson 库、Gson 或 org.json 来解析响应。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句