繁体   English   中英

从 Java 中的 Curl Post 请求中获取 Json / Resonse 正文

[英]Get Json / Resonse body from Curl Post Request in Java

这是我编写的发送 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\": \"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();
        }
    }

基本搜索显示: 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 来解析响应。

除了@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 对象。 如果它以[开头,则响应表示 JSON 数组。

您可以根据收到的response code获取errorStreaminputStream并从中获取响应。 下面的示例从流中创建一个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 您可以按照本指南

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM