使用HttpURLConnection传递文件及参数

这几天在研发公司自用的excel校验工具,需要将后台存储的excel通过http传递到excel校验服务端同时传递相关的参数,查询网上的解决方案并没有适合的,这里结合网上提供的解决方案给出我自己的解决办法:

Http传输工具类方法:

    /**
	 * 文件上传
	 * @param httpUrl         文件上传的url
	 * @param uploadFilePath  需要上传的文件
	 * @param params          传递的参数
	 * @return
	 */
	@SuppressWarnings("finally")
	public static String uploadFile(String httpUrl, String uploadFilePath, Map<String, String> params) {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		DataOutputStream ds = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		StringBuffer resultBuffer = new StringBuffer();
		String tempLine = null;
		try {
			// 统一资源
			URL url = new URL(httpUrl);
			// 连接类的父类,抽象类
			URLConnection urlConnection = url.openConnection();
			// http的连接类
			HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
			// 设置是否从httpUrlConnection读入,默认情况下是true;
			httpURLConnection.setDoInput(true);
			// 设置是否向httpUrlConnection输出
			httpURLConnection.setDoOutput(true);
			// Post 请求不能使用缓存
			httpURLConnection.setUseCaches(false);
			// 设定请求的方法,默认是GET
			httpURLConnection.setRequestMethod("POST");
			// 设置字符编码连接参数
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			// 设置字符编码
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			// 设置请求内容类型
			httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			// 设置DataOutputStream
			ds = new DataOutputStream(httpURLConnection.getOutputStream());
			String uploadFile = uploadFilePath;
			String filename = uploadFile;
			//======传递文件======
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; " + "name=\"excel" + "\";filename=\"" + filename
					+ "\"" + end);
			ds.writeBytes(end);
			FileInputStream fStream = new FileInputStream(uploadFile);
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			while ((length = fStream.read(buffer)) != -1) {
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			//======传递文件end======
			//======传递参数======
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; " + "name=\"param" + "\";filename=\"" + params.toString()
					+ "\"" + end);
			ds.writeBytes(end);
			ds.writeBytes(end);
			//======传递参数end======
			fStream.close();
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			ds.flush();
			if (httpURLConnection.getResponseCode() >= 300) {
				throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
			}
			if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inputStream = httpURLConnection.getInputStream();
				inputStreamReader = new InputStreamReader(inputStream);
				reader = new BufferedReader(inputStreamReader);
				tempLine = null;
				resultBuffer = new StringBuffer();
				while ((tempLine = reader.readLine()) != null) {
					resultBuffer.append(tempLine);
					resultBuffer.append("\n");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ds != null) {
				try {
					ds.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStreamReader != null) {
				try {
					inputStreamReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return resultBuffer.toString();
		}
	}

校验服务端部分代码:

    /**
     * excelFormatCheck
     * @param file
     * @param param
     * @return
     */
    @PostMapping("excelFormatCheck")
    public Object excelFormatCheck(@RequestParam(value = "excel", required = false) MultipartFile file, @RequestParam(value = "param", required = false) MultipartFile param) {
        Map<String, Object> result = new HashMap<>();
        Map<String, List<String>> validateResult = new HashMap();
        List<List<String>> validateResultLists = new ArrayList<>();
        try {
            if (null != file && !file.isEmpty()) {
                Gson gson = new Gson();
                Map<String, String> mapParams = new HashMap<String, String>();
                mapParams = gson.fromJson(param.getOriginalFilename(), mapParams.getClass());//转换传递的参数
                String templateId = mapParams.get("templateId");//获取模板id              
                result.put("code", 1);
                result.put("msg", "excel校验完成");
            } else {
                result.put("code", -2);
                result.put("msg", "未上传excel");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", -1);
            result.put("msg", "excel校验接口异常");
        }
        return result;
    }

测试方法:

	public static void main(String[] args) {
		String path = "F:/aa.xls";
		Map<String, String> map = new HashMap<>();
		map.put("templateId", "aa-dsa");
		String result = uploadFile("http://localhost:8002/exCheck/excelValidateCtl/excelFormatCheck", path, map);
		System.out.println(result);
	}

总结下简单说就是一旦我们将Content-Type设置为multipart/form-data原先通过k-v获取参数的方式就不再可行,因此这里除了传递真实的文件外,再传递一个仅记录文件名即所需传递参数的空文件,然后在服务端通过获取文件的文件名然后将其解析成参数即可。

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要使用Java中的DOM或SAX解析器来读取XML文件。接下来,我们可以将XML文件中的参数传递给接口,并获取返回内容。 以下是一个示例代码,演示了如何读写XML文件,并将XML中的参数传递给WishPost请求物流单号的接口: ```java import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class WishPostRequest { private static final String REQUEST_URL = "https://tracking.postoffice.co.za/VTI_Query1.asmx"; public static void main(String[] args) { try { // 读取XML文件 InputStream is = WishPostRequest.class.getResourceAsStream("wishpost_request.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(is); // 获取XML中的参数 NodeList nList = doc.getElementsByTagName("Param"); String trackingNumber = ""; for (int i = 0; i < nList.getLength(); i++) { Element element = (Element) nList.item(i); if (element.getAttribute("ParamName").equals("TrackNum")) { trackingNumber = element.getTextContent(); break; } } // 构造请求 URL url = new URL(REQUEST_URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "text/xml"); conn.setRequestProperty("SOAPAction", "http://tempuri.org/VTI_Query1"); // 将参数写入请求体 OutputStream os = conn.getOutputStream(); String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body>" + "<VTI_Query1 xmlns=\"http://tempuri.org/\">" + "<TrackNum>" + trackingNumber + "</TrackNum>" + "</VTI_Query1>" + "</soap:Body>" + "</soap:Envelope>"; os.write(xml.getBytes()); os.flush(); os.close(); // 发送请求并获取返回内容 InputStream response = conn.getInputStream(); // 处理返回内容 } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述代码中,我们首先读取了一个名为"wishpost_request.xml"的XML文件。该文件包含了我们需要传递给接口的参数。接下来,我们使用DOM解析器解析了XML文件,并获取了名为"TrackNum"的参数。 接着,我们构造了一个HTTP POST请求,并将参数写入请求体。最后,我们发送请求并获取返回内容。在实际应用中,我们需要根据返回内容进行相应的处理。 需要注意的是,上述代码仅为示例代码,实际应用中还需要进行错误处理、异常处理等相关操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值