工具包-POST请求

工具包

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * 接口请求工具
 * <p> File: HttpClientUtil.java </p>
 * <p> Date: 2022/12/9 10:51</p>
 *
 * @author 浊酒侯月
 * @version 1.0 (代码版本)
 * @since JDK8(JDK版本)
 */
public class HttpClientUtil {

    /**
     * POST 请求带参(不携带文件流方式)
     *
     * @param url   请求路径
     * @param param 参数 推荐使用转成JSON形式的字符串
     * @return 返回请求结果
     */
    public static JSONObject httpPost(String url, String param) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost method = new HttpPost(url);
        //设置请求头类型
        method.setHeader("Content-Type", "application/json");

        // post请求返回结果
        JSONObject jsonResult = new JSONObject();
        try {
            if (StringUtils.isNotBlank(param)) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(param, "UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            //设置URL加密
            URLDecoder.decode(url, "UTF-8");
            //请求发送成功,并得到响应
            int statusCode = result.getStatusLine().getStatusCode();
            //返回处理
            if (statusCode == 200) {
                String str = EntityUtils.toString(result.getEntity());
                JSONObject resObj = JSONObject.parseObject(str);
                jsonResult.put("success", true);
                jsonResult.put("message", "调用成功");
                jsonResult.put("data", resObj);
            } else if (statusCode == 500) {
                jsonResult.put("success", false);
                jsonResult.put("message", "服务器内部错误");
            } else if (statusCode == 404) {
                jsonResult.put("success", false);
                jsonResult.put("message", "接口没有找到");
            } else {
                jsonResult.put("success", false);
                jsonResult.put("message", "调用出错");
            }
            return jsonResult;
        } catch (IOException e) {
            //log.error("httpPostYs请求失败:" + url, e);
            e.printStackTrace();
        } finally {
            method.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                //log.error(String.format("httpPostYs,httpClient.close()失败:%s", url), e);
                e.printStackTrace();
            }
        }
        return jsonResult;
    }

    /**
     * POST请求,发送文件流,带token形式
     *
     * @param fileName 文件名称
     * @param file     文件
     * @param url      请求地址
     * @param token    token令牌
     * @return 外部域名的下载url
     */
    public static String uploadFileByHttpClient(String fileName, File file, String url, String token) {
        StringBuilder result = new StringBuilder();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        InputStream content = null;
        BufferedReader in = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            //HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            //头部放文件上传的head可自定义
            //httpPost.addHeader("Authorization", "Bearer " + token);

            //name:对方参数名称,file:文件流,MULTIPART_FORM_DATA:类型,fileName:文件名称
            builder.addBinaryBody("files", file, ContentType.MULTIPART_FORM_DATA, fileName);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            // 执行提交
            response = httpClient.execute(httpPost);
            //接收调用外部接口返回的内容
            HttpEntity responseEntity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回的内容都在content中
                content = responseEntity.getContent();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
            }
        } catch (Exception e) {
            //log.error("上传文件失败:",e);
            e.printStackTrace();
        } finally {
            //处理结束后关闭httpclient的链接
            try {
                httpClient.close();

                if (content != null) {
                    content.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                //log.error("上传文件失败:",e);
                e.printStackTrace();
            }
        }

        return result.toString();
    }


    /**
     * POST请求,下载文件流
     *
     * @param url         请求路径
     * @param param       参数 推荐使用转成JSON形式的字符串
     * @param pdfFilePath 选择PDF时文件输出地址
     * @return 返回请求结果
     */
    public static JSONObject downloadFile(String url, String param, String pdfFilePath) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost method = new HttpPost(url);
        //设置请求头
        method.setHeader("Content-Type", "application/json");

        // post请求返回结果
        JSONObject jsonResult = new JSONObject();
        try {
            if (StringUtils.isNotBlank(param)) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(param, StandardCharsets.UTF_8);
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            //请求发送成功,并得到响应
            int statusCode = result.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                //下载文件输出PDF文件
                HttpClientUtil.writeToPdf(result.getEntity(), pdfFilePath);
                jsonResult.put("success", true);
                jsonResult.put("type", "pdf");
                jsonResult.put("message", "下载成功");
                jsonResult.put("data", pdfFilePath);
                return jsonResult;
            } else if (statusCode == 500) {
                jsonResult.put("success", false);
                jsonResult.put("message", "服务器内部错误");
            } else if (statusCode == 404) {
                jsonResult.put("success", false);
                jsonResult.put("message", "接口没有找到");
            } else {
                jsonResult.put("success", false);
                jsonResult.put("message", "调用出错");
            }
            return jsonResult;
        } catch (IOException e) {
            //log.error("httpPostYs请求失败:" + url, e);
        } catch (Exception e) {
            //log.error(e.getMessage(), e);
        } finally {
            method.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                //log.error(String.format("httpPostYs,httpClient.close()失败:%s", url), e);
            }
        }
        return jsonResult;
    }

    /**
     * 输出pdf
     *
     * @param entity   请求返回内容
     * @param filePath 文件保存地址
     */
    public static void writeToPdf(HttpEntity entity, String filePath) throws Exception {
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            byte[] bytes = EntityUtils.toByteArray(entity);
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
            bis = new BufferedInputStream(byteInputStream);
            File file = new File(filePath);
            File path = file.getParentFile();
            //保存地址检查是否存在
            if (!path.exists()) {
                path.mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            byte[] buffer = new byte[1024];
            int length = bis.read(buffer);
            while (length != -1) {
                bos.write(buffer, 0, length);
                length = bis.read(buffer);
            }
            bos.flush();
        } catch (Exception e) {
            //log.error(e.getMessage(), e);
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                //log.error(e.getMessage(), e);
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Hutool工具包提供了几种方式来发送POST请求。其中,使用HttpUtil工具类是比较常见的方法,该工具类中封装了get和post方法,方便发送HTTP请求。你可以使用HttpUtil的post方法来发送POST请求。 另外,如果你希望更加灵活地操作HTTP请求,可以使用HttpRequest对象进行操作。HttpRequest是对HttpUtil中的方法进行封装的对象,通过使用它,你可以更加自由地设置请求参数、请求头等。 根据你的实际需求和代码复杂度,选择合适的方式来发送POST请求。你可以根据具体情况选择使用HttpUtil工具类的post方法或者使用HttpRequest对象进行操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [hutool Http 工具发送POST请求的几种方式。](https://blog.csdn.net/tiansyun/article/details/131587905)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [hutool Http 工具发送POST请求的几种方式](https://blog.csdn.net/lly576403061/article/details/131181907)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笔墨画卷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值