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?

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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 ?
6

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.