java http 传输二进制流_文件以二进制流POST的HTTP请求
时间: 2024-05-17 07:16:45 浏览: 124
你可以使用 Java 中的 HttpURLConnection 类来发送 HTTP POST 请求,将文件以二进制流的形式传输。以下是一个示例代码:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpBinaryPost {
public static void main(String[] args) throws Exception {
String url = "http://example.com/upload";
File file = new File("example.pdf");
// Create a boundary string
String boundary = Long.toHexString(System.currentTimeMillis());
// Set the content type to multipart/form-data with the specified boundary
String contentType = "multipart/form-data; boundary=" + boundary;
URL connectionUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) connectionUrl.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", contentType);
// Open a stream to write the request body
OutputStream outputStream = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
// Write the boundary and content disposition header
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append("\r\n");
// Write the content type
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append("\r\n");
writer.append("Content-Transfer-Encoding: binary").append("\r\n");
writer.append("\r\n");
// Write the file content
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// Write the end of the boundary
writer.append("\r\n");
writer.append("--" + boundary + "--").append("\r\n");
// Close the streams
inputStream.close();
outputStream.close();
writer.close();
// Read the response from the server
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
```
在上面的代码中,我们首先创建一个 HttpURLConnection 对象并设置请求的方法和请求头部。然后我们打开一个输出流并使用 PrintWriter 对象将请求体写入流中。我们首先写入一个边界字符串,然后写入文件的内容类型和文件名。接下来,我们使用 FileInputStream 读取文件内容并将其写入输出流中。最后,我们写入请求体的结束边界并关闭流。最后,我们读取服务器的响应并打印出来。
阅读全文