如何将JSONObject发送到REST服务?

3 java rest android json

从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) {
Run Code Online (Sandbox Code Playgroud)

我总是得到400错误代码.有谁知道什么是错的?

我有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();
Run Code Online (Sandbox Code Playgroud)

Mag*_*und 5

尝试设置内容类型标题:

postMethod.addRequestHeader("Content-Type","application/json");

顺便说一句,我强烈推荐泽西岛.它有一个REST 客户端库,使这些事情更容易,更易读