The correct way to PUT a JSON object to a RESTful server

13,025

Solution 1

You also need to tell the client side that it is doing a PUT of JSON. Otherwise it will try to POST something of unknown type (the detailed server logs might record it with the failure) which isn't at all what you want. (Exception handling omitted.)

URI uri = new URI("the server address goes here");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
conn.addRequestProperty("Content-Type", "application/json");
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(gson.toJson(newClient));
out.close();
// Check here that you succeeded!

On the server side, you want that to declare that it @Consumes("application/json") of course, and you probably want the method to either return a representation of the result or redirect to it (see this SO question for a discussion of the issues) so the result of your method should not be void, but rather either a value type or a JAX-RS Response (which is how to do the redirect).

Solution 2

Probably the MIME type. Try "application/json".

Share:
13,025
Thaddeus Aid
Author by

Thaddeus Aid

I currently work at Memeo Inc and teach at San Jose State University. Long time geek, semi-academic.

Updated on November 20, 2022

Comments

  • Thaddeus Aid
    Thaddeus Aid over 1 year

    I am having trouble correctly formatting my PUT request to get my server to recognise my client application's PUT command.

    Here is my section of code that puts a JSON string to the server.

    try {
        URI uri = new URI("the server address goes here");
        URL url = uri.toURL();
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(gson.toJson(newClient));
        out.close();
    } catch (Exception e) {
        Logger.getLogger(CATHomeMain.class.getName()).log(Level.SEVERE, null, e);
    }
    

    and here is the code that is supposed to catch the PUT command

    @PUT
    @Consumes("text/plain")
    public void postAddClient(String content, @PathParam("var1") String var1, @PathParam("var2") String var2) {
    

    What am I doing wrong?

  • Thaddeus Aid
    Thaddeus Aid about 13 years
    It was a cobination of wrong MIME type and the conn.setRequestMethod("PUT");
  • Thaddeus Aid
    Thaddeus Aid about 13 years
    you also need to set the connectionconn.setRequestMethod("PUT");