Android HTTPUrlConnection : how to set post data in http body?
Asked Answered
T

2

55

I've already created my HTTPUrlConnection :

String postData = "x=val1&y=val2";
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Set-Cookie", sessionCookie);
conn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));

// How to add postData as http body?

conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);

I don't know how to set postData in http body. How to do so? Would I better use HttpPost instead?

Thanks for your help.

Tran answered 16/11, 2013 at 16:35 Comment(2)
Do you want to send Json data?Overthrust
@MaximShoustin Can't I simply send it as a String ? I usually do this in iOS : NSString *string = @"x=val1&y=val2"; NSData *postData = [string dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:NO]; [request setHTTPBody:postData];Tran
O
86

If you want to send String only try this way:

String str =  "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );    
os.close();

But if you want to send as Json change Content type to:

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

and now our str we can write:

String str =  "{\"x\": \"val1\",\"y\":\"val2\"}";

Hope it will help,

Overthrust answered 16/11, 2013 at 16:47 Comment(3)
It's not valid JSON to use simple quotes in key names. :pRetch
@JulienPalard tnx, fixedOverthrust
Complete example here :) guruparang.blogspot.com/2016/01/…Hardaway
G
4

Guruparan's link in the comment above gives a really nice answer to this question. I highly recommend looking at it. Here is the principle that makes his solution work:

From what I understand, the HttpURLConnection represents the response body as an OutputStream. So you need to call something like:

get the connection's output stream

OutputStream op = conn.getOuputStream();

write the response body

op.write( [/*your string in bit form*/] );

close the output stream

op.close();

and then carry on your merry way with the connection (which you will still need to close).

Gersham answered 28/3, 2018 at 2:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.