java怎么将multipartFile作为参数向指定url发送http请求
时间: 2023-10-14 14:05:39 浏览: 122
java发送http请求
5星 · 资源好评率100%
可以使用Java中的HttpURLConnection类来发送HTTP请求,以下是一个示例代码,可以将multipartFile作为参数发送到指定的URL:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.IOUtils;
public class HttpMultipartUpload {
public static void main(String[] args) throws IOException {
String url = "http://example.com/upload";
String filePath = "/path/to/file.png";
String paramName = "file";
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
// set request method
con.setRequestMethod("POST");
// set request headers
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
// set request body
con.setDoOutput(true);
String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
String CRLF = "\r\n";
con.getOutputStream().write(("--" + boundary + CRLF).getBytes());
con.getOutputStream().write(("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + file.getName() + "\"" + CRLF).getBytes());
con.getOutputStream().write(("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName()) + CRLF).getBytes());
con.getOutputStream().write((CRLF).getBytes());
IOUtils.copy(fis, con.getOutputStream());
con.getOutputStream().write((CRLF + "--" + boundary + "--" + CRLF).getBytes());
// get response
int responseCode = con.getResponseCode();
String responseMsg = con.getResponseMessage();
System.out.println("Response code: " + responseCode);
System.out.println("Response message: " + responseMsg);
fis.close();
con.disconnect();
}
}
```
注意,这里使用了Apache Commons IO库中的IOUtils.copy方法来将文件流写入到请求体中,需要先导入该库。同时,这里使用了固定的分隔符"----WebKitFormBoundary7MA4YWxkTrZu0gW",实际应用中需要根据具体情况来设置分隔符。
阅读全文