调用hutool包调用http接口处理文件流

编程入门 行业动态 更新时间:2024-10-07 10:14:23

调用hutool包调用http<a href=https://www.elefans.com/category/jswz/34/1771365.html style=接口处理文件流"/>

调用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.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;}}

更多推荐

调用hutool包调用http接口处理文件流

本文发布于:2024-02-27 21:24:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1766773.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   文件   hutool   http

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!