http发送请求携带文件
public static void sendPostFormData(Map<String,String> map, String postUrl, InputStream inputStream, String fileName){
try {
URL url = new URL(postUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1024); // 设置分块大小
// 设置请求头
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
// 创建数据输出流
OutputStream outputStream = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"));
// 发送文件数据
byte[] buffer = new byte[1024];
int bytesRead;
writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW").append(System.lineSeparator());
writer.append("Content-Disposition: form-data; name=\"" + "file" + "\"; filename=\"" + fileName + "\"").append(System.lineSeparator());
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(System.lineSeparator());
writer.append(System.lineSeparator()).flush();
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush(); // 发送文件数据
// 添加请求体参数
map.forEach((key,value)->{
writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW").append(System.lineSeparator());
writer.append("Content-Disposition: form-data; name=\"" + key + "\"").append(System.lineSeparator());
writer.append(System.lineSeparator()).append(Objects.isNull(value)?"":value ).append(System.lineSeparator());
});
writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW--").append(System.lineSeparator());
writer.flush();
inputStream.close();
outputStream.close();
writer.close();
// 获取响应码和响应消息
connection.getResponseCode();
// 关闭连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}