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?

thegrinner
  • 11,546
  • 5
  • 41
  • 64
susparsy
  • 1,016
  • 5
  • 22
  • 38
  • 2
    please change "binnay" in your title to "binary" – MrFox Sep 11 '13 at 13:06
  • It sounds like you may want a multipart request? http://stackoverflow.com/questions/2646194/multipart-file-upload-post-request-from-java – Taylor Sep 11 '13 at 15:43

2 Answers2

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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
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.

collapsar
  • 17,010
  • 4
  • 35
  • 61