开发者

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

开发者 https://www.devze.com 2023-02-13 10:40 出处:网络
I am having trouble correctly formatting my PUT request to get my server to recognise my client application\'s PUT command.

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);
    OutputStreamW开发者_C百科riter 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?


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消