使用HttpURLConnection项目间传输附件

25 篇文章 2 订阅
14 篇文章 6 订阅
首先获取文件
@PostMapping(value = "/uploadFile")
public Result<?> uploadFile(@RequestBody String jsonStr, HttpServletRequest request, HttpServletResponse response) {
	//创建封装的返回对象
	Result<?> result = new Result<>();
	//将请求的参数转为JSONObject对象
	JSONObject jsonObj = JSONObject.parseObject(jsonStr);
	//获取到相应的请求参数
	String orderId = String.valueOf(jsonObj.get("orderId"));
	String type = String.valueOf(jsonObj.get("type"));

	//解析请求的附件列表转为JSONArray
	JSONArray json  = JSONArray.parseArray(String.valueOf(jsonObj.get("fileList")));
	//定义返回的提示
	String resultVal = "上传成功";
	//获取另一个项目需要接收附件的地址
	RequestBaseUrl info = requestBaseUrlService.getInfo();
	//拼接地址和基础的请求参数(参数中不能出现中文,否则报错)
	String actionUrl = info.getUrl3() + "/predictOrderController.do?fileReceive&orderno=" + orderId + "&type=" + type;
	
	//循环JSONArray
	for (Object o : json) {
		Map<String, File> files = new HashMap<String, File>();
		//强转发为map
		Map map = (Map)o;

		//得到文件地址
		String filePath = uploadpath + File.separator + map.get("filePath").toString();
		File file = new File(filePath);

		//判断文件是否存在
		if(!file.exists()){
			response.setStatus(404);
			result.setMessage("保存失败");
			result.setSuccess(false);
			throw new RuntimeException("文件不存在..");
		} else {
			files.put(file.getName(), file);
		}

		try {
			//调用附件传输方法,得到返回值
			resultVal = upLoadFilePost(actionUrl, files);
			//判断结果,接收附件接口返回的是Boolean也会被转为String类型,所以使用equals判断即可
			if("true".equals(resultVal)) {
				//删除附件(这里可删可不删)
				file.delete();
			} else {
				resultVal = "上传失败";
				result.setSuccess(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	 result.setMessage(resultVal);

     return result;
}
传输文件
public String upLoadFilePost(String actionUrl, Map<String, File> files) throws IOException {
	String BOUNDARY = java.util.UUID.randomUUID().toString();
	String PREFIX = "--", LINEND = "\r\n";
	String MULTIPART_FROM_DATA = "multipart/form-data";
	String CHARSET = "UTF-8";
	URL uri = new URL(actionUrl);
	HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
	conn.setReadTimeout(15 * 1000);
	conn.setDoInput(true);// 允许输入
	conn.setDoOutput(true);// 允许输出
	conn.setUseCaches(false);
	conn.setRequestMethod("POST"); // Post方式
	conn.setRequestProperty("connection", "keep-alive");
	conn.setRequestProperty("Charsert", "UTF-8");
	conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
			+ ";boundary=" + BOUNDARY);

	DataOutputStream outStream = new DataOutputStream(
			conn.getOutputStream());
	// 发送文件数据
	if (files != null)
		for (Map.Entry<String, File> file : files.entrySet()) {
			StringBuilder sb1 = new StringBuilder();
			sb1.append(PREFIX);
			sb1.append(BOUNDARY);
			sb1.append(LINEND);
			sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""
					+ file.getKey() + "\"" + LINEND);
			sb1.append("Content-Type: application/octet-stream; charset="
					+ CHARSET + LINEND);
			sb1.append(LINEND);
			outStream.write(sb1.toString().getBytes("utf-8"));	//getBytes()不加utf-8 传输中文名附件时,接收附件的地方解析文件名会乱码

			InputStream is = new FileInputStream(file.getValue());
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}

			is.close();
			outStream.write(LINEND.getBytes());
		}

	// 请求结束标志
	byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
	outStream.write(end_data);
	outStream.flush();

	// 得到响应码
	int res = conn.getResponseCode();
	if (res == 200) {
		InputStream in = conn.getInputStream();
		InputStreamReader isReader = new InputStreamReader(in);
		BufferedReader bufReader = new BufferedReader(isReader);
		String line = "";
		String data = "";
		while ((line = bufReader.readLine()) != null) {
			data += line;
		}
		outStream.close();
		conn.disconnect();
		return data;
	}
	//关闭流
	outStream.close();
	//关闭连接
	conn.disconnect();
	return null;
}
接收附件
@RequestMapping(params="fileReceive")
@ResponseBody
public Boolean fileInteraction(HttpServletRequest request, HttpServletResponse response) throws Exception {
	Boolean result = false;
    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
	//解析request,将结果放置在list中
	Map<String, List<MultipartFile>> fileMap = multiRequest.getMultiFileMap();
	for (String key : fileMap.keySet()) {
		List<MultipartFile> files = fileMap.get(key);
		for (MultipartFile file : files) {
			if (!file.isEmpty()) {
				String fileNamePath = file.getOriginalFilename();
				String[] params = fileNamePath.split("\\.");
				String filename = "";
				int i = 0;
				for (String str : params) {
					i = i + 1;
					if (StringUtils.isNotEmpty(filename)) {
						if (i==params.length) {
							filename = filename + "." + str;
						}else{
							filename = filename + "/" + str;
						}
					}else{
						filename = str;
					}
				}
				 // 文件保存路径
				 String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/wxfile/" + filename;
				 System.out.println(filePath);
				 File iFile = new File(filePath);
				 File iFileParent = iFile.getParentFile();
				 if(!iFileParent.exists()){
					 iFileParent.mkdirs();
				 }
				 // 转存文件
				 file.transferTo(new File(filePath));
				 result = true;

			 }
		}
	}
	return result;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了使用HttpURLConnection来发送和接收HTTP请求和响应,您需要按照以下步骤操作: 1. 创建HttpURLConnection对象,并将其连接到URL对象。例如: URL url = new URL("http://www.example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 2. 设置请求方法和连接属性,如连接超时和读取超时。例如: conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); 3. 添加请求头(可选)。例如: conn.setRequestProperty("User-Agent", "Android"); conn.setRequestProperty("Content-Type", "application/json"); 4. 如果POST请求,添加请求体。例如: String requestBody = "{\"username\":\"user123\",\"password\":\"pass123\"}"; OutputStream outputStream = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); writer.write(requestBody); writer.flush(); writer.close(); outputStream.close(); 5. 发送请求,获取响应码和响应数据。例如: int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder responseData = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { responseData.append(line); } reader.close(); inputStream.close(); String responseString = responseData.toString(); } 以上是使用HttpURLConnection发送和接收HTTP请求和响应的基本步骤。具体实现需根据具体的业务需求和网络情况进行调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值