0

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

Rob
  • 4,123
  • 3
  • 33
  • 53
  • Well, first off, how is the server *expecting* the file to be uploaded? Will it accept raw bytes in a `POST`? Probably not. It is more likely to expect a `multipart/form-data` encoded `POST`, or even a `PUT`. What you are sending right now is an `application/x-www-form-urlencoded` encoded `POST` – Remy Lebeau Oct 09 '17 at 21:38
  • Sorry, that's right, it's going to expect a multipart/form-data POST – Rob Oct 09 '17 at 21:39
  • Possible duplicate of [Sending files using POST with HttpURLConnection](https://stackoverflow.com/questions/11766878/sending-files-using-post-with-httpurlconnection) – Remy Lebeau Oct 09 '17 at 21:40

0 Answers0