public static String sendPostMultipart(String url, Map<String,Object> params, Map headermap) throws Exception {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
log.info("==sendPostMultipart发送的地址:"+ url);
log.info("==sendPostMultipart发送的请求参数:"+ JSON.toJSONString(params));
log.info("==sendPostMultipart头参数:"+JSON.toJSONString(headermap));
try {
String mimeBoundary = IdUtils.fastSimpleUUID();
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//主要是是这个
conn.setRequestProperty("Content-Type","multipart/form-data; boundary="+mimeBoundary);
for(Object key : headermap.keySet()){
conn.setRequestProperty(key.toString(), StringUtils.nullObj2Str(headermap.get(key)));
}
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
StringBuffer body = new StringBuffer();
Set<String> keys = params.keySet();
//拼接请求内容
for (String key : keys) {
body.append("--").append(mimeBoundary);
body.append("\r\n");
body.append(String.format("Content-Disposition: form-data; name=\"%s\"", key));
body.append("\r\n\r\n");
body.append(StringUtils.nullObj2Str(params.get(key)));
body.append("\r\n");
}
body.append("--").append(mimeBoundary).append("--").append("\r\n");
out.print(body);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
log.info(" ==sendPostMultipart的result结果:"+result);
} catch (Exception e) {
log.info("==sendPostMultipart发送 POST 请求出现异常!"+e);
e.printStackTrace();
if(e.getMessage().length() > 500){
result = "==sendPostMultipart发送 POST 请求出现异常!"+ e.getMessage().substring(0,500);
} else {
result = "==sendPostMultipart发送 POST 请求出现异常!"+ e.getMessage();
}
}finally{//使用finally块来关闭输出流、输入流
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
log.info("==sendPostMultipart的请求结果:"+result);
return result;
}
主要目的是拼接成如下的报文