java 如何将 JSONObject 发送到 REST 服务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3022566/
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
How to send a JSONObject to a REST service?
提问by Magnus Eklund
Retrieving data from the REST Server works well, but if I want to post an object it doesn't work:
从 REST 服务器检索数据效果很好,但如果我想发布一个对象,它就不起作用:
public static void postJSONObject(int store_type, FavoriteItem favorite, String token, String objectName) {
        String url = "";
        switch(store_type) {
            case STORE_PROJECT:
                url = URL_STORE_PROJECT_PART1 + token + URL_STORE_PROJECT_PART2; 
                //data = favorite.getAsJSONObject();
            break;
        }
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postMethod = new HttpPost(url);
        try {   
            HttpEntity entity = new StringEntity("{\"ID\":0,\"Name\":\"Mein Projekt10\"}");
            postMethod.setEntity(entity);
            HttpResponse response = httpClient.execute(postMethod);
            Log.i("JSONStore", "Post request, to URL: " + url);
            System.out.println("Status code: " + response.getStatusLine().getStatusCode());
        } catch (ClientProtocolException e) {
I always get a 400 Error Code. Does anybody know whats wrong?
我总是收到 400 错误代码。有人知道出了什么问题吗?
I have working C# code, but I can't convert:
我有可用的 C# 代码,但无法转换:
 System.Net.WebRequest wr = System.Net.HttpWebRequest.Create("http://localhost:51273/WSUser.svc/pak3omxtEuLrzHSUSbQP/project");
            wr.Method = "POST";
            string data = "{\"ID\":1,\"Name\":\"Mein Projekt\"}";
            byte [] d = UTF8Encoding.UTF8.GetBytes(data);
            wr.ContentLength = d.Length;
            wr.ContentType = "application/json";
             wr.GetRequestStream().Write(d, 0, d.Length);
            System.Net.WebResponse wresp = wr.GetResponse();
            System.IO.StreamReader sr = new System.IO.StreamReader(wresp.GetResponseStream());
            string line = sr.ReadToEnd();
回答by Magnus Eklund
Try setting the content type header:
尝试设置内容类型标题:
postMethod.addRequestHeader("Content-Type", "application/json");
postMethod.addRequestHeader("Content-Type", "application/json");
Btw, I strongly recommend Jersey. It has a REST client librarywhich makes these kind of things much easier and more readable
回答by CommonsWare
Your C# is different than your Java, and not just in syntax.
您的 C# 与您的 Java 不同,而不仅仅是在语法上。
Your C# sends an application/jsonentity to the server via HTTP POST. I'll leave it up to HTTP purists as to whether that's appropriate use of POST (vs. PUT).
您的 C#application/json通过 HTTP POST 向服务器发送一个实体。至于这是否适合使用 POST(与 PUT),我将留给 HTTP 纯粹主义者。
Your Java creates a form, with a field of jsonString(whose value is the JSON), and sends an application/x-www-form-urlencodedentity to the server containing that form. 
您的 Java 创建一个表单,其字段为jsonString(其值为 JSON),并将一个application/x-www-form-urlencoded实体发送到包含该表单的服务器。
回答by Brad Hein
I would go right to the server err_log or equivelant error log. The server knows why it rejected your request. If you don't have access, set up your own test server and duplicate the issue there so you can review the logs =)
我会直接转到服务器 err_log 或等效的错误日志。服务器知道为什么拒绝您的请求。如果您无权访问,请设置您自己的测试服务器并在那里复制问题,以便您可以查看日志 =)

