java 将 JSON 对象放入 RESTful 服务器的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5129762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The correct way to PUT a JSON object to a RESTful server
提问by Thaddeus Aid
I am having trouble correctly formatting my PUT request to get my server to recognise my client application's PUT command.
我无法正确格式化我的 PUT 请求以让我的服务器识别我的客户端应用程序的 PUT 命令。
Here is my section of code that puts a JSON string to the server.
这是我将 JSON 字符串放入服务器的代码部分。
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 命令的代码
@PUT
@Consumes("text/plain")
public void postAddClient(String content, @PathParam("var1") String var1, @PathParam("var2") String var2) {
What am I doing wrong?
我究竟做错了什么?
回答by Donal Fellows
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.)
您还需要告诉客户端它正在执行 JSON 的 PUT。否则它会尝试 POST 一些未知类型的东西(详细的服务器日志可能会记录失败),这根本不是你想要的。(省略了异常处理。)
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 questionfor 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).
在服务器端,您@Consumes("application/json")
当然希望声明它,并且您可能希望该方法返回结果的表示或重定向到它(有关问题的讨论,请参阅此 SO问题)因此您的结果方法不应该是void
,而是值类型或 JAX-RS Response
(这是如何进行重定向)。
回答by Charlie Martin
Probably the MIME type. Try "application/json".
可能是 MIME 类型。尝试“应用程序/json”。