HttpURLConnection访问上传文件接口

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();
	}
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值