Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add json to the body of an http post in java

I'm trying to post some JSON data in java for an Android app I'm working on. Is the below valid or do I need to push the JSON string in a different way?

HttpPost httpost = new HttpPost("http://test.localhost"); httpost.setEntity(new StringEntity("{\"filters\":true}")); httpost.setHeader("Accept", "application/json"); httpost.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); //... other java code to execute the apache httpclient 

Thank you in advance

like image 438
Toran Billups Avatar asked May 14 '11 02:05

Toran Billups


People also ask

Can you send JSON in post?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

How do I make a POST request with JSON content body using HttpURLConnection?

JSONObject cred = new JSONObject(); JSONObject auth=new JSONObject(); JSONObject parent=new JSONObject(); cred. put("username","adm"); cred. put("password", "pwd"); auth. put("tenantName", "adm"); auth.


1 Answers

You should set the Content-Type header to "application/json". Everything else looks good.

like image 67
laz Avatar answered Sep 22 '22 23:09

laz