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": "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(); } }
Advertisement
Answer
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.