How to send a JSONObject to a REST service?

2020-03-05 02:48发布

Retrieving data from the REST Server works well, but if I want to post an object it doesn't work:

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?

I have working C# code, but I can't convert:

 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();

3条回答
Lonely孤独者°
2楼-- · 2020-03-05 03:14

Try setting the content type header:

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

Btw, I strongly recommend Jersey. It has a REST client library which makes these kind of things much easier and more readable

查看更多
Emotional °昔
3楼-- · 2020-03-05 03:21

Your C# is different than your Java, and not just in syntax.

Your C# sends an application/json entity 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).

Your Java creates a form, with a field of jsonString (whose value is the JSON), and sends an application/x-www-form-urlencoded entity to the server containing that form.

查看更多
一夜七次
4楼-- · 2020-03-05 03:33

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

查看更多
登录 后发表回答