如何将数据映射发送到 Web 服务?

How to send data map to a web service?

我有我的网络服务代码:

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public static Response fillData(final Map<String, Object> data) {  
       ...  
       final byte[] file = ...
       return Response.ok(file).build();

如何将地图数据发送到服务?

final javax.ws.rs.core.Response reponse = client.target(URL_REST).path("/path").request(MediaType.APPLICATION_JSON).post(?);

这是我的 JSON 文件的示例:

{
  "activity" : {
    "code" : "ACT_014",
    "title" : "FIGHTING"
  },
  "adress" : {
    "place" : "",
    "number" : ""
  }
}

谢谢。

您尝试过通过 HttpURLConnection 吗?

URL url = new URL(URL_REST);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        String input = "{\"activity\" :....}";

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

...并收集输出响应数据

我不得不使用 MediaType.APPLICATION_JSON_TYPE:

.post(Entity.entity(data, MediaType.APPLICATION_JSON_TYPE), Response.class)

如果你知道主机地址,你也可以使用 postman、curl 或 soapUI。

如果对客户端技术没有要求,可以使用Restlet框架和库org.json。以下是代码示例:

ClientResource cr = new ClientResource("http://...");
JSONObject obj = new JSONObject();
obj.put("activity", "my value");
(...)
cr.post(new JsonRepresentation(obj));

希望对您有所帮助, 蒂埃里