1

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?

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
Thaddeus Aid
  • 169
  • 1
  • 1
  • 17

2 Answers2

5

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).

Community
  • 1
  • 1
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
3

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

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263