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

📅 2026-12-01 👤 拼多多助力营销技巧 📂 手赚APP 👁️ 112 次阅读

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请求

*/

publicString 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"));

* Listparams = new ArrayList<>();

*/

public static HttpResponse doGetTestByURI(Listparams, 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) {

Mapparams = 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;

}

}

推荐文章

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧