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?

2 Answers 2

2

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

string result = Convert.ToBase64String(Encoding.UTF8.GetBytes(utf8Text));
Sign up to request clarification or add additional context in comments.

Comments

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?

1 Comment

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?

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.