這是我撰寫的發送 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();
}
}
uj5u.com熱心網友回復:
基本搜索顯示: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 庫、Gs??on 或 org.json 來決議回應。
uj5u.com熱心網友回復:
您可以獲取errorStream或inputStream基于response code您收到的資訊并從中獲取回應。下面的示例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庫將其轉換為。您可以按照本指南
uj5u.com熱心網友回復:
除了@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 物件{。如果它以 a 開頭,[則回應表示一個 JSON 陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/484409.html
