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

阿曼阿加瓦尔

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

检索Play框架Java中POST请求中发送的请求正文字符串

当Java中的请求失败时,如何获取http响应正文?

无法在http请求中设置POST正文

无法将JSON作为正文发送给GO中的HTTP POST请求

在Application Insights中查看POST请求正文

带JSON正文的POST请求

如何在php中获取POST正文?

在ActionFilter中获取请求正文

如何在Slim中访问POST请求的JSON请求正文?

为什么在此cURL调用中的请求正文中收到格式错误的JSON?

在Android的OKhttp中通过POST请求发送JSON正文

C#-POST请求中的正文内容

如何在JMETER中打印或获取HTTP POST请求正文

Android Volley Post请求在正文中带有json对象,并在String中获取响应

如何使用PHP(cURL)中的post方法在带有标头的正文中发送JSON数据

在Moleculer中获取正文POST请求

使用Retrofit Android在POST请求中从JSON正文中排除某些字段

在使用JAVA的Azure函数中,如何获取请求正文

如何从Swift中的WKWebView获取POST请求正文?

请求正文在Post中为空

如何从POST请求中读取正文

在POST请求中从正文检索JSON-Java

无法从 python 中的 JSON WEB API 请求中获取正文

使用 Slim 框架从 axios POST 请求中获取正文

在 Application Insights 中查看 POST 请求正文(JAVA 示例)

带有标题和 JSON 正文的 Volley 中的 POST 请求

POST 请求的 JSON 正文

如何在java中获取失败的HTTP请求正文?

如何在php中的Curl请求中仅获取响应的正文