2021-09-28->HttpClientUtil 工具包

2023-05-16

package com.ruoyi.common.utils;/**
 * @Package com.ruoyi.common.utils
 * @data 2021/4/3 下午6:00
 * @Version 佛祖保佑 永无BUG
 */

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.cloudgain.CommonConfig;
import com.ruoyi.common.utils.http.HttpRequestUtil;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.*;

/**
 * @data 2021/4/3 下午6:00
 */
public class HttpClientUtil {
    /**
     * httpClient的get请求方式
     * 使用GetMethod来访问一个URL对应的网页实现步骤:
     * 1.生成一个HttpClient对象并设置相应的参数;
     * 2.生成一个GetMethod对象并设置响应的参数;
     * 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
     * 4.处理响应状态码;
     * 5.若响应正常,处理HTTP响应内容;
     * 6.释放连接。
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset) {
        //1.生成HttpClient对象并设置参数
        HttpClient httpClient = new HttpClient();
        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //2.生成GetMethod对象并设置参数
        GetMethod getMethod = new GetMethod(url);
        //设置get请求超时为5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //设置请求重试处理,用的是默认的重试处理:请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
        //3.执行HTTP GET 请求
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            //4.判断访问的状态码
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("请求出错:" + getMethod.getStatusLine());
            }
            //5.处理HTTP响应内容
            //HTTP响应头部信息,这里简单打印
            Header[] headers = getMethod.getResponseHeaders();
            for(Header h : headers) {
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            //读取HTTP响应内容,这里简单打印网页内容
            //读取为字节数组
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            //读取为InputStream,在网页内容数据量大时候推荐使用
            //InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            //发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("请检查输入的URL!");
            e.printStackTrace();
        } catch (IOException e) {
            //发生网络异常
            System.out.println("发生网络异常!");
        } finally {
            //6.释放连接
            getMethod.releaseConnection();
        }
        return response;
    }

    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
        //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        //添加请求参数
//        postMethod.addParameter("commentId", json.getString("commentId"));
        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    public static String doPost(String url, Map<String, Object> paramMap) {
        // 获取输入流
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置httpClient连接主机服务器超时时间:15000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 创建post请求方法实例对象
        PostMethod postMethod = new PostMethod(url);
        // 设置post请求超时时间
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);

      NameValuePair[] nvp = null;
        // 判断参数map集合paramMap是否为空
        if (null != paramMap && paramMap.size() > 0) {
            // 不为空
            // 创建键值参数对象数组,大小为参数的个数
            nvp = new NameValuePair[paramMap.size()];
            // 循环遍历参数集合map
            Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
            // 获取迭代器
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();

      int index = 0;
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                // 从mapEntry中获取key和value创建键值对象存放到数组中
                try {
                    nvp[index] = new NameValuePair(mapEntry.getKey(),
                            new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                index++;
            }
        }
        // 判断nvp数组是否为空
        if (null != nvp && nvp.length > 0) {
            // 将参数存放到requestBody对象中
            postMethod.setRequestBody(nvp);
        }
        // 执行POST方法
        try {
            int statusCode = httpClient.executeMethod(postMethod);
            // 判断是否成功
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method faild: " + postMethod.getStatusLine());
            }
            // 获取远程返回的数据
            is = postMethod.getResponseBodyAsStream();
            // 封装输入流
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

      StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp).append("\r\n");
            }

            result = sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 释放连接
            postMethod.releaseConnection();
        }
        return result;
    }


}


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

2021-09-28->HttpClientUtil 工具包 的相关文章

  • [Android] Dialog篇

    一 AlertDialog 简单Dialog xff1a Dialog dialog span class token operator 61 span new AlertDialog Builder span class token pu
  • 谷歌pixel刷机_如何在Google Pixel上禁用(或启用)应用建议

    谷歌pixel刷机 Android 11 introduced a feature for Google Pixel phones called App Suggestions The launcher will suggest diffe
  • [Android] 菜单加水平分割线

    选项菜单加水平分隔线 menu的item加group分组设置setGroupDividerEnabled为true span class token operator lt span menu xmlns android span clas
  • 快速安装Pytorch和Torchvision

    文章目录 1 Linux下激活自己的虚拟环境并查看Python版本2 查看需要安装的Pytorch和Torchvision版本3 直接命令行安装3 1 如果不报错的话3 2 ERROR Could not install packages
  • 【Darknet-53】YOLOv3 backbone Darknet-53 详解

    文章目录 1 模型计算量与参数量2 Darknet 53网络3 感谢链接 1 模型计算量与参数量 模型计算量与参数量的计算方式主要有两种 xff0c 一种是使用thop库 xff0c 一种是使用torchsummaryX 使用pip ins
  • 【DeeplabV3+】DeeplabV3+网络结构详解

    文章目录 1 常规卷积与空洞卷积的对比1 1 空洞卷积简介1 2 空洞卷积的优点 2 DeeplabV3 43 模型简介3 DeeplabV3 43 网络代码4 mobilenetv2网络代码5 感谢链接 聊DeeplabV3 43 网络前
  • 【YOLOv3 decode】YOLOv3中解码理解decode_box

    文章目录 1 解码是什么意思2 代码解读3 生成网格中心 代码详解4 按照网格格式生成先验框的宽高 代码详解5 感谢链接 1 解码是什么意思 在利用YOLOv3网络结构提取到out0 out1 out2之后 xff0c 不同尺度下每个网格点
  • 【DeeplabV3+ MIoU】DeeplabV3+计算评价指标

    文章目录 1 分割常用评价指标1 1 什么是MIoU1 2 什么是PA1 2 什么是MPA 2 根据混淆矩阵计算评价指标2 1 计算MIoU2 2 计算PA2 3 计算MPA 3 计算 MIoU 总体代码4 compute mIoU 函数
  • 【MobileNetV3】MobileNetV3网络结构详解

    文章目录 1 MobileNetV3创新点2 block变成了什么样2 1 总体介绍2 2 SE模块理解2 3 ReLu6和hardswish激活函数理解 3 网络总体结构4 代码解读5 感谢链接 在看本文前 xff0c 强烈建议先看一下之
  • 【Smooth L1 Loss】Smooth L1损失函数理解

    文章目录 1 引言2 L1 Loss3 L2 Loss4 Smooth L1 Loss5 曲线对比分析6 参考链接 1 引言 目标检测任务的损失函数由Classificition Loss和Bounding Box Regeression
  • Command errored out with exit status 1类似问题解决方案

    在使用pip install onnx时遇到如下错误 xff1a Building wheels for collected packages onnx Building wheel for onnx setup py error ERRO
  • 【tensorflow onnx】TensorFlow2导出ONNX及模型可视化教程

    文章目录 1 背景介绍2 实验环境3 tf2onnx工具介绍4 代码实操4 1 TensorFlow2与ONNX模型导出4 2 ONNX正确性验证4 3 TensorFlow2与ONNX的一致性检查4 4 多输入的情况4 5 设定输入 输出
  • 如何在Microsoft Edge中更改主页

    By default Microsoft Edge opens with a custom New Tab page full of content Luckily it s easy to open the browser with a
  • 【PaddlePaddle onnx】PaddlePaddle导出ONNX及模型可视化教程

    文章目录 1 背景介绍2 实验环境3 paddle onnx export函数简介4 代码实操4 1 PaddlePaddle与ONNX模型导出4 2 ONNX正确性验证4 3 PaddlePaddle与ONNX的一致性检查4 4 多输入的
  • 【linux命令】如何查看文件/文件夹所占空间大小

    文章目录 1 查看文件大小1 1 方法1 xff1a ls lh1 2 方法2 xff1a du sh1 3 方法3 xff1a stat 2 查看文件夹所占大小2 1 方法1 xff1a du2 2 方法2 xff1a ncdu 1 查看
  • Github+Hexo搭建个人博客(图文详解)

    文章目录 使用Github 43 hexo搭建个人博客 不会让小伙伴们走弯路 1 准备工作 xff1a 安装两个我们本次所需要使用的软件 xff1a 2 注册Github账号以及建立仓库 xff1a https github com htt
  • 2019-12-14-FTP服务器搭建

    title FTP服务器搭建 date 2019 12 14 15 34 19 updated 2019 12 14 15 34 19 categories 服务器 搭建 网络 tags FTP服务器 目录 什么是FTP服务器本地FTP服务
  • 小程序开发需要多少钱?

    小程序开发的费用 xff1a 一般几千到几万不等 看具体要求 其实开发小程序的价格主要取决于你要做多少页面和要做的页面和功能的复杂程度 如果是行业内比较成熟的标准化系统就会相对便宜点 至于开发多少钱 xff0c 这样看你采用以下哪种模式 x
  • Docker 1 - 基本使用

    Docker 文章目录 Docker一 关于 Docker安装 Docker1 查看版本2 安装3 卸载 Docker 常见命令查看Docker 磁盘使用情况清理磁盘停止Docker 服务 二 镜像查看已安装镜像拉取镜像删除镜像查找镜像方式
  • Spring MVC的异常处理和友好页面

    加油 xff0c 新时代打工人 xff01 Spring MVC详细环境配置和入门 Spring MVC 响应数据和结果视图 SpringMVC实现三种文件上传的方式 实现之前把Spring MVC环境配置完成 xff0c 参考以上文章 S

随机推荐