Amit Gawali
Amit Gawali

Reputation: 280

How to add object in Request body via URL and HttpURLConnection class

I am referring to this question and I have following piece of code:

String urlParameters  = "param1=a&param2=b&param3=c";
byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
int    postDataLength = postData.length;
String request        = "http://example.com/index.php";
URL    url            = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
   wr.write( postData );
}

but I want to add array of attributes in my request body, so my request data looks like this:

{
  "accountEnabled": true,
  "city": "Delhi",
  "country": "India",
  "department": "Human Resources",
  "displayName": "Adam G",
  "passwordProfile": {
    "password": "Test1234",
    "forceChangePasswordNextSignIn": false
  },
  "officeLocation": "131/1105",
  "postalCode": "98052",
  "preferredLanguage": "en-US",
  "state": "MH",
 }

How can I send array here as I have 'passwordProfile' as object? Any help will be appreciated!

Upvotes: 1

Views: 1493

Answers (2)

Alex Frignani
Alex Frignani

Reputation: 1

To send "items" into body of the request, you can do this:

declare:

String json = "{\"accountEnabled\": true, \"city\": \"Delhi\",..................";

Then

URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
OutputStream os = con.getOutputStream();
os.write(json.getBytes());

In this case you are sending a json, so important is:

con.setRequestProperty("Content-Type", "application/json");

Upvotes: 0

Ganesh Toni
Ganesh Toni

Reputation: 36

to send json object as mentioned in your question first you need to change the content type as below

conn.setRequestProperty("Content-Type","application/json");

then using Jackson 2 library you can get json string value from any object which will be our post data. for eg:

ObjectMapper mapper = new ObjectMapper();
byte[] postData       = mapper.writeValueAsString(staff).getBytes( StandardCharsets.UTF_8 );

that's all and your code will work fine.

Upvotes: 1

Related Questions