调用hutool包调用http接口处理文件流-文件的上传下载工具类

hutool工具类get请求获取流:
InputStream inputStream = HttpRequest.get(fileUrl).execute().bodyStream();

hutool工具类post请求上传文件流:
String resp = HttpRequest.post(url).header(Header.CONTENT_TYPE.getValue(), ContentType.MULTIPART.getValue()).form(params).execute().body();

完成代码



import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.*;

import java.io.IOException;

@Slf4j
@Service
public class HttpUtils {


    public int SUCCESS_CODE = 200;
    public int FILED_CODE = 500;


    public static String getCurrentToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
//        String token = request.getHeader("token");
        LoginUserBO principal = (LoginUserBO) SecurityUtils.getAuthentication().getPrincipal();
        String token = principal.getToken();
        return token;
    }


    /**
     * 有参POST请求
     */
    public <T> String doPostTestByParam(String url, T t) {

        // 请求地址
//        String url = "http://localhost:8889/consumer/post";
        // post请求
        HttpClient httpClient = null;
        HttpPost postMethod = null;
        HttpResponse response = null;
        String responseContent = null;
        try {
            // 获取http客户端
            httpClient = HttpClients.createDefault();
            postMethod = new HttpPost(url);
            // 自定义对象
//            User user = new User();
            // 设置请求头
            postMethod.addHeader("Content-Type", "application/json;charset=utf8");
            // 封装请求体
            postMethod
                    .setEntity(new StringEntity(JSON.toJSONString(t), Charset.forName("UTF-8")));
            // 发送请求
            response = httpClient.execute(postMethod);
            // 获取响应结果
            int statusCode = response.getStatusLine().getStatusCode();
            // 响应对象
            HttpEntity httpEntity = response.getEntity();
            // 响应的字符串
            responseContent = EntityUtils.toString(httpEntity, "UTF-8");
            //释放资源
            EntityUtils.consume(httpEntity);
            return responseContent;
        } catch (IOException e) {
            log.info("请求异常, 错误信息为: {} ", e.getMessage());
            return null;
        }
    }


    /**
     * 有参GET请求 添加请求配置
     * params.add(new BasicNameValuePair("key", "123456"));
     * params.add(new BasicNameValuePair("id", "123123"));
     * List<NameValuePair> params = new ArrayList<>();
     */
    public static HttpResponse doGetTestByURI(List<NameValuePair> params, String scheme, String host, int port, String path) {
//        String url = "http://localhost:8889/consumer/get";
//        String currentToken = getCurrentToken();
        //  获取httpClient客户端
        HttpClient httpClient = HttpClientBuilder.create().build();
        //  发送请求
        HttpResponse httpResponse = null;
        URI uri = null;
        try {
            uri = new URIBuilder()
                    .setScheme(scheme)
                    .setHost(host)
                    .setPort(port)
                    .setPath(path)
                    .setParameters(params)
                    .build();
            //  创建Post请求
            HttpGet httpPost = new HttpGet(uri);
//            httpPost.setHeader("Authorization", "Bearer " + currentToken);
            httpResponse = httpClient.execute(httpPost);

            // 配置请求信息
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000) // 连接超时时间
                    .setConnectionRequestTimeout(5000) //请求超时时间
                    .setSocketTimeout(5000) // 读写超时时间
                    .setRedirectsEnabled(true) // 是否重定向 默认true开启
                    .build();
            httpPost.setConfig(requestConfig);

            // 4 响应状态码 响应信息
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            log.info("响应状态码为: {} ", statusCode);

            // 响应信息
            HttpEntity httpEntity = httpResponse.getEntity();
            log.info("响应内容为: {} ", EntityUtils.toString(httpEntity));

            //释放资源
            EntityUtils.consume(httpEntity);
            return httpResponse;
        } catch (Exception e) {
            log.info("请求异常, 错误信息为: {} ", e.getMessage());
            return httpResponse;
        }

    }


    /**
     * 上传文件服务器
     *
     * @param file
     * @return
     */
    public JSONArray upLoadFileService(MultipartFile file, String url) {
        Map<String, Object> params = new HashMap<>();
        JSONArray jsonArray = new JSONArray();
        params.put("files", createIs(file));
        String resp = HttpRequest.post(url).header(Header.CONTENT_TYPE.getValue(), ContentType.MULTIPART.getValue()).form(params).execute().body();
        log.info("fileServerResp:{}", resp);
        JSONObject respJson = JSONUtil.parseObj(resp);
        String fileId = "";
        if (SUCCESS_CODE == respJson.getInt("code") && !respJson.getJSONArray("data").isEmpty()) {
            jsonArray = respJson.getJSONArray("data");
        }
        return jsonArray;
    }


    /**
     * 文件流转换
     *
     * @param file
     * @return
     */
    public InputStreamResource createIs(MultipartFile file) {
        InputStreamResource isr = null;
        try {
            isr = new InputStreamResource(file.getInputStream(), file.getOriginalFilename());
        } catch (IOException e) {
            log.info("文件流转换异常:{}", e);
        }
        return isr;
    }


    public  InputStream downloadFile(String fileUrl) throws IOException {
        InputStream inputStream = null;
        try {
            inputStream = HttpRequest.get(fileUrl).execute().bodyStream();
            System.out.println("文件下载完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }


}








  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值