1.导包
参考上篇文章
2.具体实现
通常实现上传文件,web端通过form表单enctype="multipart/form-data"即可实现,若不通过浏览器,可通过HttpURLConnection实现上传
private static String boundary = "--boundary";//分隔符,任意字符串都可以
private static String prefix = "--";
private static String nextLine = "\r\n";//回车换行符
//pmap:body中的参数
//fMap:上传的文件
public static String postGeneralUrlByMultipartFile(String url,Map<String, Object> pmap,Map<String, MultipartFile> fMap,String encoding) throws Exception{
URL url1 = new URL(url);
HttpURLConnection conn=(HttpURLConnection)url1.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
conn.setRequestProperty("Connection", "keep-alive");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
if(pmap!=null && !pmap.isEmpty()){
writeParam(pmap,out);
}
if(fMap!=null && !fMap.isEmpty()){
writeFile(fMap, out);
}
String end = prefix + boundary + prefix + nextLine;//标识结束
out.write(end.getBytes());
out.flush();
out.close();
//获取响应
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),encoding));
String result = "";
String line;
while((line=in.readLine())!=null){
result += line;
}
in.close();
return result;
}
//写入file文件
private static void writeFile(Map<String, MultipartFile> map,OutputStream out) throws Exception{
try {
if(map!=null && !map.isEmpty()){
StringBuilder sb = new StringBuilder();
Set<Entry<String, MultipartFile>> entrySet = map.entrySet();
for (Entry<String, MultipartFile> entry : entrySet) {
if(entry!=null && entry.getValue()!=null){
sb = new StringBuilder();
sb.append(prefix).append(boundary).append(nextLine);
sb.append("Content-Disposition: form-data; name=\"")
.append(entry.getKey()).append("\";filename=\"")
.append(entry.getValue().getOriginalFilename()).append("\"")
.append(nextLine);
sb.append("Content-Type: ").append(entry.getValue().getContentType()).append(nextLine);
sb.append(nextLine);
out.write(sb.toString().getBytes());
out.write(entry.getValue().getBytes());
out.write(nextLine.getBytes());
out.flush();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//写入参数
private static void writeParam(Map<String, Object> map,OutputStream out) throws Exception{
try {
if(map!=null && !map.isEmpty()){
StringBuilder sb = new StringBuilder();
Set<Entry<String, MultipartFile>> entrySet = map.entrySet();
for (Entry<String, MultipartFile> entry : entrySet) {
if(entry!=null ){
sb.append(prefix).append(boundary).append(nextLine);
sb.append("Content-Disposition: form-data; name=\"")
.append(entry.getKey()).append("\"").append(nextLine);
sb.append(nextLine);
sb.append(entry.getValue());
sb.append(nextLine);
}
}
out.write(sb.toString().getBytes());
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}