Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Sending a byte[] array via Http POST

I am able to do a POST of a parameters string. I use the following code:

String parameters = "firstname=john&lastname=doe";
URL url = new URL("http://www.mywebsite.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestMethod("POST");

OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(parameters);
out.flush();
out.close();
connection.disconnect();

However, I need to do a POST of binary data (which is in form of byte[]).

Not sure how to change the above code to implement it.
Could anyone please help me with this?

like image 320
OceanBlue Avatar asked Jun 15 '11 15:06

OceanBlue


3 Answers

Take a look here Sending POST data in Android

But use ByteArrayEntity.

byte[] content = ...
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new ByteArrayEntity(content));           
HttpResponse response = httpClient.execute(httpPost);
like image 82
Fabio Falci Avatar answered Oct 08 '22 01:10

Fabio Falci


You could base-64 encode your data first. Take a look at the aptly named Base64 class.

like image 45
kabuko Avatar answered Oct 08 '22 02:10

kabuko


These links might be helpful:

  • Android httpclient file upload data corruption and timeout issues
  • http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html
  • http://forum.springsource.org/showthread.php?108546-How-do-I-post-a-byte-array
like image 22
R3D3vil Avatar answered Oct 08 '22 01:10

R3D3vil