/**
* post请求formdata数据
* @author zongx
* @throws Exception
*
*/
public static String postFormData(String postUrl,Map<String,String> postParam,List<MultipartFile> postFiles) throws Exception{
URL url=new URL(postUrl);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
int timeout = (StringUtils.isNumeric(httpTimeout) ? Integer.parseInt(httpTimeout) : 10) * 1000;
conn.setConnectTimeout(timeout*1000);
conn.setReadTimeout(timeout*1000);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=1234");
OutputStream out=conn.getOutputStream();
// 参数上传
Iterator<Entry<String, String>> it = postParam.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
// key
out.write("--1234\r\n".getBytes());
String key = entry.getKey();
out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n").getBytes());
out.write("\r\n".getBytes());
// value
String value = entry.getValue();
out.write(value.getBytes());
out.write("\r\n".getBytes());
}
// photo 上传
InputStream fin =null;
byte[] fileBytes = null;
for(int i = 0; i < postFiles.size(); i++) {
if(i != postFiles.size() - 1) {
out.write("--1234\r\n".getBytes());
String name = postFiles.get(i).getOriginalFilename();
out.write(("Content-Disposition: form-data; name=\""+name+"\";filename=\""+name+"\"\r\n").getBytes());
out.write("Content-Type: application/octet-stream\r\n".getBytes());
fin=postFiles.get(i).getInputStream();
fileBytes=new byte[fin.available()];
fin.read(fileBytes);
out.write("\r\n".getBytes());
out.write(fileBytes);
out.write("\r\n".getBytes());
fin.close();
}else{
out.write("--1234\r\n".getBytes());
String name = postFiles.get(i).getOriginalFilename();
out.write(("Content-Disposition: form-data; name=\""+name+"\";filename=\""+name+"\"\r\n").getBytes());
out.write("Content-Type: application/octet-stream\r\n".getBytes());
fin=postFiles.get(i).getInputStream();
fileBytes=new byte[fin.available()];
fin.read(fileBytes);
out.write("\r\n".getBytes());
out.write(fileBytes);
out.write("\r\n".getBytes());
out.write("--1234--\r\n".getBytes());
fin.close();
}
}
out.flush();
out.close();
//返回的参数
int respCode=conn.getResponseCode();
if(respCode==200) {
BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
StringBuilder builder=new StringBuilder();
String line;
while((line=reader.readLine())!=null) {
builder.append(line);
}
System.out.println(builder.toString());
return builder.toString();
}
return null;
}
}
来源:CSDN
作者:阿萨德执行
链接:https://blog.csdn.net/u010365717/article/details/100566138