Android HTTPUrlConnection : how to set post data in http body? - android

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.

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,

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).

Related

Received length differs from sent length

I am using an Android app to send a base64 encoded string to a CherryPy server. The Android code works like this:
URL url = new URL("http://foo.bar/blabla");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(base64s.length());
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(base64s.getBytes());
So, you'd say the amount of bytes sent equals the amount of bytes in the Content-Length header. However, in Python, when I run this:
cl = cherrypy.request.headers['Content-Length']
rawbody = cherrypy.request.body.read()
print "{} bytes, {}".format(len(rawbody), cl)
The numbers cl and len(rawbody) are different.
How can that be?
Maybe you forgot to close the stream with out.close(); ?
your server sould send a "close header" so the client will no its end stream for him.

Android: Send a file as an array of bytes using HttpURLConnection

I want to send a file via a POST HTTP request but can't find how to handle it first...
I would do this with a string parameter:
String html_params = "myparam=myparam";
byte[] outputInBytes = html_params.getBytes("UTF-8");
URL url = new URL("http://www.myurl.com/senddata.asp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "text/html");
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.close();
response = conn.getResponseCode();
However I have no idea of how to transform and send a file as an array of bytes instead of a string...
Thanks for your help

Some character didn't post with Json Post - getting 500 reponse

I have prepared one API, and I want to send one specific data with json posting.
My code works fine during working with Fiddler or site side.
But the problem is why some character didn't send, when we use Android version as a client device.
For example:
string a="mn✈" // correct on any device (android,site,Fiddler,...)
string b="mn✉" //correct on any device except(android) //getting 500 reponse
String requestURL = Utils.SERVER_URL + "PostJsonFeatures";
HttpURLConnection conn = (HttpURLConnection) new URL(requestURL).openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
JSONObject postDataParams = new JSONObject();
postDataParams.put("Features", getAttributes());
postDataParams.put("productId", productId);
postDataParams.put("groupId", catId);
postDataParams.put("brandId", PrefManager.getInstance(context).getCompanyId());
postDataParams.put("languageId", PrefManager.getInstance(context).getLanguageApi());
DataOutputStream printout = new DataOutputStream(conn.getOutputStream ());
printout.write(postDataParams.toString().getBytes());
printout.flush ();
printout.close ();
You can decode to string and pass in url.
String parseString = URLDecoder.decode(URLEncoder.encode(myString, "UTF-8"), "ISO-8859-1");

How to make POST call using HttpURLConnection with JSON data in Android

please help me out with this problem.
I want to make a POST call with JSON data that should appear in body to request but i am not able to do that. I made POST call and getting data but data is not in JSON format.
Code :
data = "{'mobile':'"+mobile_number+"','password':'"+mypassword+"'}";
byte[] dataPost = data.getBytes();
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setRequestProperty("Accept", "application/json");
//urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("charset", "UTF8");
urlConnection.setUseCaches(false);
OutputStream os = urlConnection.getOutputStream();
os.write(dataPost);
os.close();
Result is coming like below
body:
{'a':'b','c':'d'}:""
Please Help me. i am new to android Development.
Thanks

Basic authentication to access assembla rest apis from android

I want to use assembla apis from android environment for my project.
I am trying to do basic authentication as follow :
String authentication = "username:password";
String encoding = Base64.encodeToString(authentication.getBytes(), 0);
URL url = new URL("https://www.assembla.com/");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + encoding);
conn.setDoOutput(true);
conn.connect();
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
I am getting 400 and Bad Request in output.
is there something wrong with URL that i am using or some other thing is going wrong?
It looks like the question was answered here. You need to use Base64.NO_WRAP flag when encoding username-password pair:
String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
By default the Android Base64 util adds a newline character to the end of the encoded string. This invalidates the HTTP headers and causes the "Bad request".
The Base64.NO_WRAP flag tells the util to create the encoded string without the newline character thus keeping the HTTP headers intact.
REST API with HTTP Authentication Output:- I got the result
String authentication = "username:password";
String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", "Basic " + encoding);
conn.connect();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
Content = sb.toString();

Categories

Resources