在Web服务中使用JSON字节数组和application / x-www-form-urlencoded

有3个问题。 我正在使用Java Restful webservices并且请求是HTTP POST

  1. 客户端如何发送JSON数据以及application / x-www-form-urlencoded的MediaType。 是否可以使用字节数组?

  2. 如何使用在服务器端以byte []格式发送的JSON数据以及application / x-www-form-urlencoded的MediaType?

  3. 我可以使用Postman客户端以字节数组格式发送JSON吗?

  1. (1)邮递员将自动对JSON进行URL编码。 只需输入一个键,值就是JSON。 (2)是的,但您希望首先对字节数组进行Base64编码。 请参阅Java 8的Base64.Encoder.encodeToString 。 如果您不使用Java 8,则可能需要获取外部库。

  2. (1)如果您只是发送了url-endoded JSON,并且想要POJOify JSON,那么您应该使用像Jackson这样的库。 你可以做点什么

     @Path("/encoded") public class EncodedResource { @POST @Path("/json") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response getResponse(@FormParam("json") String json) throws Exception { ObjectMapper mapper = new ObjectMapper(); Hello hello = mapper.readValue(json, Hello.class); return Response.ok(hello.hello).build(); } public static class Hello { public String hello; } } 

    我用Postman测试了这个,在键中键入json ,在值中键入{"hello":"world"} ,它运行正常。 响应是world

    (2)如果您要对Base64进行编码,那么您需要执行类似的操作

     @POST @Path("/base64") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response getResponse(@FormParam("base64") String base64) throws Exception { String decoded = new String(Base64.getDecoder().decode(base64)); ObjectMapper mapper = new ObjectMapper(); Hello hello = mapper.readValue(decoded, Hello.class); return Response.ok(hello.hello).build(); } public static class Hello { public String hello; } 

    我也用Postman对它进行了测试,它运行正常。 我用过这段代码

     String json = "{\"hello\":\"world\"}"; String encoded = Base64.getEncoder().encodeToString(json.getBytes()); 

    要获取编码字符串(即eyJoZWxsbyI6IndvcmxkIn0= ),请将其作为值并将base64作为键。 随着对上述方法的请求,我获得了相同的world结果。

  3. 我认为这应该在上面介绍。