There are 3 questions. I am using Java Restful webservices and request is HTTP POST
how can client send JSON data along with MediaType of application/x-www-form
(1) Postman will automatically url-encode the JSON. Just enter a key and value is the JSON. (2) Yes, but you will want to Base64 encode the byte array first. See Java 8's Base64.Encoder.encodeToString. If you're not using Java 8, you'll probably want to get an external library.
(1) If you just send the url-endoded JSON, and you want to POJOify the JSON, then you should work with a library like Jackson. You could do something like
@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;
}
}
I've tested this with Postman, typing json
into the key and {"hello":"world"}
into the value, and it works fine. The reponse is world
(2) If you are going to Base64 encode it, then you need to do something like
@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;
}
I've tested this also with Postman, and it works fine. I used this code
String json = "{\"hello\":\"world\"}";
String encoded = Base64.getEncoder().encodeToString(json.getBytes());
to get an encode string (which is eyJoZWxsbyI6IndvcmxkIn0=
), put that as the value and base64
as the key. With a request to the method above, I get the same world
result.
I think this should be covered above.