0

I need to send a binary message which is divided to 2 parts:

  1. The first part is 4 bytes and it has some information (say an integer)
  2. The second part has an XMLtext stream.

I have never done something like this before, how can I do this?

My code is something like this:

public String serverCall(String link, String data){
         HttpURLConnection connection;
         OutputStreamWriter writer = null;

         URL url = null;
         String parameters = data;

         try
         {
             url = new URL(link);
             connection = (HttpURLConnection) url.openConnection();
             connection.setDoOutput(true);
             connection.setRequestProperty("Content-Type", "text/xml");
             connection.setRequestMethod("POST");    

             writer = new OutputStreamWriter(connection.getOutputStream());
             writer.write(parameters);
             writer.flush();
             writer.close();
          }
          catch(IOException e)
          {
              e.printStackTrace();
          }
}

How do I set the XML to be 4 bytes and how do I have 4 bytes of text before it?

2
  • 2
    please change "binnay" in your title to "binary" Commented Sep 11, 2013 at 13:06
  • It sounds like you may want a multipart request? stackoverflow.com/questions/2646194/… Commented Sep 11, 2013 at 15:43

2 Answers 2

2

(Info) The HTTP protocol uses method PUT to "transport a file on the server" (instead of POST).

The transport of binary data better not have a content type "text/..." but "application/bin".

You however could send the XML as "text/xml; charset=UTF-8", and use your own header

connection.setHeader("MyCode",
    String.format("%02x%02x%02x%02x", bytes[0], bytes[1], bytes[2], bytes[3]));

If you send all as binary, do not use a Writer (converts bytes to some character encoding), but a Stream (BufferedOutputStream). The XML as:

byte[] xmlBytes = xml.getBytes("UTF-8");

UTF-8 if there is no other encoding mentioned in <?xml ...>.

The close() already flushes, so flush() is not needed.

Sign up to request clarification or add additional context in comments.

2 Comments

application/octet-stream would be a more appropriate content type for arbitrary binary data, would it not?
@Dev indeed, I personally use that, I love that archaic name; octet=byte.
0

If the binary portion of your message are mere 4 bytes, percent-encode it and send it as an additional url-parameter. alternatively, add it to the existing xml stream.

the java classes Uri and URLEncoder provide the necessary methods.

Comments

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.