11

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?

OceanBlue
  • 9,142
  • 21
  • 62
  • 84

3 Answers3

9

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);
Community
  • 1
  • 1
Fabio Falci
  • 308
  • 2
  • 7
  • It is taking a very long time (8 sec) to execute this line "httpPost.setEntity(new ByteArrayEntity(content));" sometimes in my code. Do you have any idea why this can happen ? – insanely_sin Mar 28 '17 at 18:28
6

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

kabuko
  • 36,028
  • 10
  • 80
  • 93
  • 1
    +1 for the idea. Unfortunately I cannot do use Base64 since the server does not expect it. (I cannot make change to the server as it caters to many client applications) – OceanBlue Jun 16 '11 at 19:43