/** * HttpPost请求发送 */ public static String sendHttpDataFile(String sendContent, String url, Map<String, String> content, MultipartFile file) { log.info("接口请求地址--{}|接口请求报文--{}", url, sendContent); String result = ""; CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(Charset.forName("utf-8")); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题 builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename());// 文件流 HttpEntity entity = builder.build(); httpPost.setEntity(entity); httpPost.setHeader("access_token", content.get("token")); HttpResponse response = httpClient.execute(httpPost);// 执行提交 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { // 将响应内容转换为字符串 result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8")); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
SpringBoot HTTP发送文件
最新推荐文章于 2024-04-19 10:39:54 发布