Java调用post 上传文件带参详解
时间: 2023-09-16 13:08:50 浏览: 103
在Java中调用post上传文件带参,可以使用Java自带的HttpURLConnection或者第三方库如Apache HttpClient。以下是使用HttpURLConnection的示例代码:
```java
public static void uploadFileWithParams(String urlString, Map<String, String> params, String filePath) throws IOException {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
String boundary = "---------------------------" + System.currentTimeMillis();
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream outputStream = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
for (Map.Entry<String, String> entry : params.entrySet()) {
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"").append("\r\n");
writer.append("Content-Type: text/plain; charset=UTF-8").append("\r\n");
writer.append("\r\n");
writer.append(entry.getValue()).append("\r\n");
}
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + new File(filePath).getName() + "\"").append("\r\n");
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(filePath)).append("\r\n");
writer.append("\r\n");
writer.flush();
Files.copy(Paths.get(filePath), outputStream);
outputStream.flush();
writer.append("\r\n");
writer.append("--" + boundary + "--").append("\r\n");
writer.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// Handle success response
} else {
// Handle error response
}
connection.disconnect();
}
```
这段代码中,我们首先创建一个URL对象,然后使用它创建一个HttpURLConnection对象。我们设置请求方式为POST,开启输出流,设置Content-Type为multipart/form-data,指定boundary值。然后我们依次写入参数和文件信息,其中参数使用Content-Disposition设置name属性,文件使用Content-Disposition设置name和filename属性,使用URLConnection.guessContentTypeFromName获取文件类型。最后我们将文件内容拷贝到输出流中,关闭输出流,等待服务器响应。在响应中,我们可以根据responseCode判断上传是否成功。
阅读全文