简体   繁体   English

如何将 hashmap 作为 JsonObject 发送到 Java 中的 Web 服务

[英]How to send hashmap as JsonObject to a webservice in Java

I am trying to make a POST request with a hashmap.我正在尝试使用 hashmap 发出 POST 请求。 The accepted format by the webservice is given below. Web 服务接受的格式如下所示。

{ 
"students": [
         {
            "firstName": "Abc",
            "lastName": "XYZ",
            "courses": [
            "Math",
            "English"
            ]
          }
}

This is my code这是我的代码

HttpClient client2 = HttpClient.newBuilder().build();
HttpRequest request2 = HttpRequest.newBuilder()
          .uri(URI.create(POST_URI))
          .header("Content-Type", "application/json")
          .POST(new JSONObject(myMap))
          .build();

However, this doesn't work.但是,这不起作用。 All the examples I have seen so far only accept string as POST parameter and not map.到目前为止,我看到的所有示例都只接受字符串作为 POST 参数,而不接受 map。

In your case it seems that you are using the java http client introduced in Java 11. This client required a BodyPublisher to send POST requests.在您的情况下,您似乎正在使用 Java 11 中引入的 java http 客户端。此客户端需要 BodyPublisher 来发送 POST 请求。

The java.net.http.BodyPublishers class provide you a method named #ofString(String body) that you can use to send body. java.net.http.BodyPublishers class 为您提供了一个名为#ofString(String body)的方法,您可以使用它来发送正文。

So you can just build your HttpRequest like that:所以你可以像这样构建你的 HttpRequest :

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(POST_URI))
    .header("Content-Type", "application/json")
    .POST(BodyPublishers.ofString(yourBody))
    .build();

In this case you need to pass a string to the ofString method, so you can use a library like Jackson or Gson.在这种情况下,您需要将字符串传递给ofString方法,因此您可以使用 Jackson 或 Gson 之类的库。 I don't know how to do this using Gson but using Jackson it is very simple:我不知道如何使用 Gson 但使用 Jackson 非常简单:

ObjectMapper mapper = new ObjectMapper();

String yourBody = mapper.writeValueAsString(yourMap);

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(POST_URI))
    .header("Content-Type", "application/json")
    .POST(BodyPublishers.ofString(yourBody))
    .build();

That's all:)就这样:)

EDIT: After a second reading, I would like to point out that you cannot send java objects as is in an http request.编辑:经过第二次阅读,我想指出您不能像在 http 请求中那样发送 java 对象。 You already need to transform your objects in a readable format for the server like json or XML.您已经需要将对象转换为服务器的可读格式,例如 json 或 XML。 Java objects are part of the programs we write, the Http protocol is not able to pass these objects as is. Java 对象是我们编写的程序的一部分,Http 协议无法按原样传递这些对象。 That's why we use an intermediate format, thus the server is able to read this format and transform it back into an object这就是我们使用中间格式的原因,因此服务器能够读取此格式并将其转换回 object

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

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