我创建了一个参数字符串的 POST,使用的下面的代码:
String parameters = "firstname=john&lastname=doe";
URL url = new URL("http://www.mywebsite.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(parameters);
out.flush();
out.close();
connection.disconnect();
但是,我需要创建一个二进制数据的POST(byte[]形式)。
不知道如何改变上面的代码来实现。
请问谁知道呢?
可以使用以下代码将二进制数据发送为 POST 请求:
byte[] data = ... // 你的二进制数据
URL url = new URL("http://www.mywebsite.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream os = connection.getOutputStream();
os.write(data);
os.flush();
os.close();
connection.disconnect();
需要注意的是,在这种情况下,不需要设置 "Content-Type" 请求属性,因为您已经将二进制数据直接写入输出流。