java http 传输二进制流_文件以二进制流POST的HTTP请求
时间: 2024-06-08 22:10:54 浏览: 2
可以使用Java的HttpURLConnection类来实现文件以二进制流POST的HTTP请求。下面是一个示例代码:
```java
import java.io.*;
import java.net.*;
public class HttpPostBinaryFile {
public static void main(String[] args) throws IOException {
String url = "http://example.com/upload";
String fileName = "example.png";
File file = new File(fileName);
FileInputStream input = new FileInputStream(file);
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setRequestProperty("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
OutputStream output = connection.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
output.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
input.close();
output.close();
}
}
```
在这个示例代码中,我们使用了Java的FileInputStream类来读取二进制文件,使用URLConnection类来发送HTTP请求,并在请求头中设置了Content-Type和Content-Disposition属性来指定文件类型和文件名。然后我们使用OutputStream类将文件内容写入HTTP请求的主体中。
当然,在实际应用中,我们还需要根据服务器的要求设置其他HTTP请求头和主体内容。