使用Jsoup发送请求上传和下载文件
场景是自己的web端需要上传文件到别人的接口上,
我自己的页面上传文件到后台就不需要说什么了,关键是要把文件直接上传到接口,当然还有其他参数。
Controller
@RequestMapping(value="/uploadExcel", produces = "application/json;charset=UTF-8") public @ResponseBody String uploadExcel(@RequestParam Map<String, String> data, @RequestParam("file") MultipartFile file) throws Exception { return service.uploadExcel(data, file); }
service
public String uploadExcel(Map<String, String> data, MultipartFile file) throws Exception { return doPostFileRequest("/item/direction/coupon/uploadCouponExcel", data, file.getInputStream(), file.getOriginalFilename()); }
util
protected String doPostFileRequest(String url, Map<String, String> param, InputStream fis, String fileName) throws Exception {try { Connection conn = Jsoup.connect(user.getJdDomain() + url); if (param != null) { conn.data(param); } conn.data("file", fileName, fis); Connection.Response response = conn.timeout(DEFAULT_TIME_OUT).ignoreContentType(true).maxBodySize(0).followRedirects(true).method(Connection.Method.POST).execute(); return response.body(); } catch (UncheckedIOException var7) { throw new IOException(var7); } }
上面是上传,就是data方法
下载文件代码,请求别人的接口获取文件流,然后返回前台下载。
@RequestMapping(value="/exportSyncResult", produces = "application/json;charset=UTF-8") public void exportSyncResult(@RequestParam Map<String, String> data, HttpServletResponse response) throws Exception { Connection.Response response1 = service.exportSyncResult(data); byte[] bytes = response1.bodyAsBytes(); String s = response1.contentType(); String header1 = response1.header("Content-Disposition"); response.addHeader("Content-Disposition", header1); response.setContentType(s); response.getOutputStream().write(bytes); }
@Override public Connection.Response exportSyncResult(Map<String, String> data) throws Exception { return getResponseIn("/item/direction/coupon/exportSyncResult", data); }
public Connection.Response getResponseIn(String url, Map<String, String> param) throws Exception { getParam(param); User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user"); try { Connection conn = Jsoup.connect(user.getJdDomain() + url); if (param != null) { conn.data(param); } Connection.Response response = conn.timeout(DEFAULT_TIME_OUT).ignoreContentType(true).maxBodySize(0).followRedirects(true).method(Connection.Method.GET).execute(); return response; } catch (UncheckedIOException var7) { throw new IOException(var7); } }