Skip to content Skip to sidebar Skip to footer

Sending Json Object To Api By Using Http Post

I want to add header 'Content-Type' 'application/json'. But I am not been able to do this due to api 23 in android. OutputStream os= null; os=httpcl

Solution 1:

I assume that you are trying to make a network call to some API which expects you to add Headers to the HTTP calls you are making and the content-type data is JSON.

If that is your case then you would have to specify the Headers to the instance to respective class with which you are trying to connect..

for example if you are using HttpURLConnection then it would look like this

HttpURLConnectionhttpURLConnection= (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST"); // hear you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
            httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json` 
            httpURLConnection.connect();

and when you are posting some data to the instance of the HttpURLConnection you can do it like this...

JsonObjectjsonObject=newJsonObject();
            jsonObject.addProperty("para_1", "arg_1");
            jsonObject.addProperty("para_2", "arg_2");

            DataOutputStreamwr=newDataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(jsonObject.toString());
            wr.flush();
            wr.close();

Post a Comment for "Sending Json Object To Api By Using Http Post"