使用Springboot封装好的发送post请求的工具类

 更新时间:2024年09月14日 10:52:43   作者:Peter447  
本文介绍了在Springboot中封装发送HTTP请求的工具类,并提供了普通的HTTP请求工具类代码和Response类的使用示例,这些工具类可为开发者提供便利性和参考价值,帮助提高开发效率

Springboot封装发送post请求工具类

Springboot封装好的发送http请求的工具类代码

(最下面有普通的工具类):

  public static Response sendPostRequest(String url, Map<String, Object> params){
            RestTemplate client = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            HttpMethod method = HttpMethod.POST;
            // 以什么方式提交,自行选择,一般使用json,或者表单
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            //将请求头部和参数合成一个请求
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
            //执行HTTP请求,将返回的结构使用Response类格式化
            ResponseEntity<Response> response = client.exchange(url, method, requestEntity, Response.class);
    
            return response.getBody();
        }

再附带一个我使用的Response类

/**
 * @author peter
 * @version 1.0
 * @title Response
 */
public class Response<T> implements Serializable {

    public void setSuccess(boolean success) {
        this.success = success;
    }

    private boolean success;
    private T result;
    private String errorCode;
    private String errorMsg;

    public Response() {
    }

    public Response(T result) {
        this.success = true;
        this.result = result;
    }

    public Response(boolean flag, T result) {
        if (flag) {
            this.success = true;
            this.result = result;
        } else {
            this.success = false;
            this.errorCode = (String) result;
        }

    }

    public Response(String errorCode) {
        this.success = false;
        this.errorCode = errorCode;
    }

    public Response(String errorCode, String errorMsg) {
        this.success = false;
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public boolean isSuccess() {
        return this.success;
    }

    public T getResult() {
        return this.result;
    }

    public void setResult(T result) {
        this.success = true;
        this.result = result;
    }

    public String getErrorCode() {
        return this.errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.success = false;
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return this.errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        } else if (o != null && this.getClass() == o.getClass()) {
            Response response = (Response) o;
            boolean isErrorCode = !this.errorCode.equals(response.errorCode) ? false : this.result.equals(response.result);
            return this.success != response.success ? false : (isErrorCode);
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        int result1 = this.success ? 1 : 0;
        result1 = 31 * result1 + this.result.hashCode();
        result1 = 31 * result1 + this.errorCode.hashCode();
        return result1;
    }

    @Override
    public String toString() {
        return "Response{" +
                "success=" + success +
                ", result=" + result +
                ", errorCode='" + errorCode + '\'' +
                ", errorMsg='" + errorMsg + '\'' +
                '}';
    }
}

普通的发送http请求的工具类

import com.zhang.railway.common.Response;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpUtil {

	/**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("Content-Type","application/json");
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
 
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 简单解析execute和submit有什么区别

    简单解析execute和submit有什么区别

    这篇文章主要介绍了简单解析execute和submit有什么区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • Spring的BeanFactoryPostProcessor接口示例代码详解

    Spring的BeanFactoryPostProcessor接口示例代码详解

    这篇文章主要介绍了Spring的BeanFactoryPostProcessor接口,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-02-02
  • 浅谈Java安全之C3P0的使用

    浅谈Java安全之C3P0的使用

    本文主要介绍了浅谈Java安全之C3P0的使用,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • 使用SpringBoot实现Redis多数据库缓存

    使用SpringBoot实现Redis多数据库缓存

    在我的系统中,为了优化用户行为数据的存储与访问效率,我引入了Redis缓存,并将数据分布在不同的Redis数据库中,通过这种方式,可以减少单一数据库的负载,提高系统的整体性能,所以本文给大家介绍了使用SpringBoot实现Redis多数据库缓存,需要的朋友可以参考下
    2024-06-06
  • Java正则之贪婪匹配、惰性匹配

    Java正则之贪婪匹配、惰性匹配

    这篇文章主要介绍了Java正则之贪婪匹配、惰性匹配的相关资料,需要的朋友可以参考下
    2015-03-03
  • SpringCloud项目集成Feign、Hystrix过程解析

    SpringCloud项目集成Feign、Hystrix过程解析

    这篇文章主要介绍了SpringCloud项目集成Feign、Hystrix过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • mybatis plus generator 根据数据库自动生成实体类的实现示例

    mybatis plus generator 根据数据库自动生成实体类的实现示例

    本文主要介绍了mybatis plus generator 根据数据库自动生成实体类的实现示例,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-09-09
  • SpringBoot通过AOP与注解实现入参校验详情

    SpringBoot通过AOP与注解实现入参校验详情

    这篇文章主要介绍了SpringBoot通过AOP与注解实现入参校验详情,文章从相关问题展开全文内容详情,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-05-05
  • Java中HashMap获取值的几种方式汇总

    Java中HashMap获取值的几种方式汇总

    这篇文章主要介绍了Java中HashMap获取值的几种方式汇总,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • Spring Controller接收前端JSON数据请求方式

    Spring Controller接收前端JSON数据请求方式

    这篇文章主要为大家介绍了Spring Controller接收前端JSON数据请求方式详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07

最新评论