java http请求发送文件流
时间: 2023-11-22 14:06:11 浏览: 31
以下是Java发送文件流的示例代码:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpFileUpload {
public static void main(String[] args) {
String urlStr = "http://example.com/upload";
String file = "/path/to/file";
String fileName = "example.txt";
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
OutputStream outputStream = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n");
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n");
writer.append("Content-Type: text/plain\r\n\r\n");
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append("\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--\r\n");
writer.close();
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该示例代码使用Java的HttpURLConnection类发送HTTP POST请求,并将文件流作为请求体发送到指定的URL。在示例代码中,需要将`urlStr`变量设置为目标URL,`file`变量设置为要上传的文件路径,`fileName`变量设置为要上传的文件名。在实际应用中,需要根据具体情况进行修改。