HttpClient服务器不保存文件在本地直接请求接口

场景:客户端(浏览器)A---->选择文件上传---->服务器B---->中转文件---->服务器C---->返回结果---->服务器B---->客户端A

有时候在项目中需要把上传的文件中转到第三方服务器,第三方服务器提供一个接收文件的接口。

而我们又不想把文件先上传到服务器保存后再通过File来读取文件上传到第三方服务器,我们可以使用HttpClient来实现。

因为项目使用的是Spring+Mybatis框架,文件的上传采用的是MultipartFile,而FileBody只支持File。

所以这里采用MultipartEntityBuilder的addBinaryBody方法以数据流的形式上传。

httpPostInvoke请求文件和String,httpPostInvokeJson只请求Json

这里需要引入两个jar包:httpclient-4.4.jar和httpmime-4.4.jar

Maven pom.xml引入

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.4</version>
    </dependency>

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.UUID;

@Slf4j
public class NetworkUtil {

    public static int CONNECTTIMEOUT = 30000;

    public static int SOCKETTIMEOUT = 90000;

    public static String httpPostInvoke(String url, Map<String, Object> map, Map<String, Object> headerMap) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTTIMEOUT).setSocketTimeout(SOCKETTIMEOUT).build();
        httpPost.setConfig(requestConfig);

        if (headerMap != null && headerMap.size() > 0) {
            for (Map.Entry entry : headerMap.entrySet()) {
                if (entry.getValue() != null) {
                    httpPost.setHeader(entry.getKey().toString(), (String) entry.getValue());
                }
            }
        }

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        for (Map.Entry entry : map.entrySet()) {
            if (entry.getValue() != null) {
                if (entry.getValue() instanceof byte[]) {
                    multipartEntityBuilder.addBinaryBody(entry.getKey().toString(), (byte[]) entry.getValue(), ContentType.MULTIPART_FORM_DATA, UUID.randomUUID().toString().replaceAll("-", "")+".jpg");
                } else {
                    multipartEntityBuilder.addPart(entry.getKey().toString(), new StringBody(entry.getValue().toString(), ContentType.TEXT_PLAIN));
                }
            }
        }
        HttpEntity reqEntity = multipartEntityBuilder.build();

        httpPost.setEntity(reqEntity);

        CloseableHttpResponse response = httpclient.execute(httpPost);
        String str = null;
        try {
            str = EntityUtils.toString(response.getEntity());
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                log.info("StatusLine:" + response.getStatusLine() + " executing request:" + httpPost.getRequestLine() + " request params:" + map + " response result:" + str);
                
            }

            log.info("executing request:" + httpPost.getRequestLine() + " request params:" + map + " response result:" + str);
            EntityUtils.consume(response.getEntity());
            return str;
        } finally {
            response.close();
            try {
                httpclient.close();
            } catch (IOException e) {
                log.error(String.format("httpPostInvoke error %s", e.getMessage()), e);
            }
        }
    }

    public static String httpPostInvokeJson(String url, Map<String, Object> bodyMap, Map<String, Object> headerMap) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTTIMEOUT).setSocketTimeout(SOCKETTIMEOUT).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("content-type", "application/json;charset=UTF-8");
        if (headerMap != null && headerMap.size() > 0) {
            for (Map.Entry entry : headerMap.entrySet()) {
                if (entry.getValue() != null) {
                    httpPost.setHeader(entry.getKey().toString(), (String) entry.getValue());
                }
            }
        }

        String params = JSON.toJSONString(bodyMap);
        StringEntity entity = new StringEntity(params, Charset.forName("UTF-8"));
        httpPost.setEntity(entity);

        response = httpClient.execute(httpPost);
        String str = null;
        try {
            str = EntityUtils.toString(response.getEntity());
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                log.info("StatusLine:" + response.getStatusLine() + " executing request:" + httpPost.getRequestLine() + " request params:" + bodyMap + " response result:" + str);
                
            }

            log.info("executing request:" + httpPost.getRequestLine() + " request params:" + bodyMap + " response result:" + str);
            EntityUtils.consume(response.getEntity());
            return str;
        } finally {
            response.close();
            try {
                httpClient.close();
            } catch (IOException e) {
                log.error(String.format("httpPostInvoke error %s", e.getMessage()), e);
            }
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值