简体   繁体   中英

Post byte array in parameter

I am writing my http post header.

POST /\r\n
Content-Length=...\r\n
\r\n\r\n
file1=(bytearray data)&file2=(bytearray data)

I am not sure how I can put the bytearray data there

If you want to do it all by hand, you only need to encode your parameters properly :

byte[] array1 = new byte[10];
byte[] array2 = new byte[10];

StringBuilder builder = new StringBuilder();

builder.append("POST /\r\n");
builder.append("Content-Length=...\r\n");
builder.append("\r\n\r\n");
builder.append("file1=");
builder.append(URLEncoder.encode(new String(array1),"UTF-8"));
builder.append("&file2=");
builder.append(URLEncoder.encode(new String(array2),"UTF-8"));

Or you can use something more clear or more standard with HttpURLConnection :

byte[] array1 = new byte[10];
byte[] array2 = new byte[10];

StringBuilder parameters = new StringBuilder();

parameters.append("file1=");
parameters.append(URLEncoder.encode(new String(array1),"UTF-8"));
parameters.append("&file2=");
parameters.append(URLEncoder.encode(new String(array2),"UTF-8"));

String request = "http://domain.com";
URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset","UTF-8");
connection.setRequestProperty("Content-Length",Integer.toString(parameters.toString().getBytes().length));

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(parameters.toString());
wr.flush();
wr.close();
connection.disconnect();

More info :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM