How to send a JSONObject to a REST service?

Retrieving data from a REST server works well, but if I want to publish an object, it does not 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 error code 400. Does anyone know what is wrong?

I have working C # code, but I can not 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
source share
3 answers

Try customizing the content type header:

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

Btw, I highly recommend Jersey . It has a REST client library that makes these things a lot easier and more readable.

+5
source

# Java, .

# application/json HTTP POST. HTTP- , POST ( PUT).

Java jsonString ( JSON) application/x-www-form-urlencoded , .

+2

err_log . , . , , =)

-1

Source: https://habr.com/ru/post/1749576/


All Articles