This is the method I have written which sends a POST request to send an Email. I am able to send the email and get the Response Code 200 Ok. But I don't know how to get the JSON Response and convert it into an Object. 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\": \"[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();
}
}
CodePudding user response:
A basic search reveals: 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.
CodePudding user response:
You can get errorStream
or inputStream
based on the response code
you receive and get the response from it. Below example creates a BufferedReader
from the stream
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. Below will store data into 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. You may follow this guide
CodePudding user response:
In addition to the answer by @mdre
I use the org.json library to convert responses into JSON Objects. 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 {
. If it starts with a [
the response represents a JSON array.