3

I try to use HTTP POST to send some Data to a Server. The Server expects the binary Data in $_POST['file'].

        URL url = new URL("http://example.com");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        OutputStream outputStream =  connection.getOutputStream();
        outputStream.write("file=".getBytes());

                //byte[] buffer contains the data
            outputStream.write(buffer);         
        outputStream.close();

Is OutputStream.write the right method to write into the stream? Do I have to handle the string ("file=") other then the buffer?

Charles
  • 48,924
  • 13
  • 96
  • 136
Non
  • 1,828
  • 2
  • 16
  • 21

2 Answers2

2

I recommend converting your data to Base64 String (Compatibility with all systems).

string result = Convert.ToBase64String(Encoding.UTF8.GetBytes(utf8Text));
davecon
  • 141
  • 7
0

Yes, to write text with POST, you will need to write to `OutputStream.

For parameters, you will need to create a String of key-value pair (separated with &) and write the byte array of that data in OutputStream as follows:

String parameterString = "file=" + parameters.get("file") + "&" + "other=" + parameter.get("other");
outputStream.write(parameterString.getBytes("UTF-8"); //Don't forget, HTTP protocol supports UTF-8 encoding.
outputStream.flush();

To do file upload with URLConnection, see BalusC's article How to use java.net.URLConnection to fire and handle HTTP requests?

Community
  • 1
  • 1
Buhake Sindi
  • 82,658
  • 26
  • 157
  • 220
  • The problem is, that i have to send the concent of a binary file. I don't think that I can just add it to "file=", can I? – Non Jan 25 '12 at 17:38