使用HttpClient转发请求

使用HttpClient转发请求

转发MultipartFile文件流请求

  1. pom相关依赖
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
		<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.4</version>
        </dependency>
  1. post方法
/**
	@param url 请求的地址
	@param equipment 其他formData数据
	@param file 转发的流文件
	@param token 验证身份信息
*/
public String postMultipart(String url, String equipment, MultipartFile file, String token) {
        String result = null;
        try {
            //提取到文件名
            String fileName = file.getName();
            //转换成文件流
            InputStream is = file.getInputStream();
            //接收文件的服务器地址
            String uploadURL = serviceUri+url;
            //创建HttpClient
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(uploadURL);
            httpPost.setHeader("token",token);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            /*绑定文件参数,传入文件流和contenttype,此处也可以继续添加其他formdata参数*/
            builder.addBinaryBody("excelFile",is, ContentType.MULTIPART_FORM_DATA,fileName);
            builder.addTextBody("equipment",equipment);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            //执行提交
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();

            //将响应的内容转换成字符串
            result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));

            if(is != null){
                is.close();
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return result;
    }
posted @ 2022-08-18 13:30  芏筄  阅读(224)  评论(0)    收藏  举报