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

时间:2025-03-05 20:40:28

Springboot封装好的发送http请求的工具类代码(最下面有普通的工具类):

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

再附带一个我使用的Response类

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

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

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

    public Response() {
    }

    public Response(T result) {
         = true;
         = result;
    }

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

    }

    public Response(String errorCode) {
         = false;
         = errorCode;
    }

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

    public boolean isSuccess() {
        return ;
    }

    public T getResult() {
        return ;
    }

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

    public String getErrorCode() {
        return ;
    }

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

    public String getErrorMsg() {
        return ;
    }

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

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

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

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

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

import ;
import .*;
import ;

import .*;
import ;
import ;
import ;
import ;

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 = ();
            // 设置通用的请求属性
            ("Content-Type","application/json");
            ("accept", "*/*");
            ("connection", "Keep-Alive");
            ("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            ();
            // 获取所有响应头字段
            Map<String, List<String>> map = ();
            // 遍历所有的响应头字段
//            for (String key : ()) {
//                (key + "--->" + (key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    ()));
            String line;
            while ((line = ()) != null) {
                result += line;
            }
        } catch (Exception e) {
            ("发送GET请求出现异常!" + e);
            ();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    ();
                }
            } catch (Exception e2) {
                ();
            }
        }
        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 = ();
            // 设置通用的请求属性
            ("accept", "*/*");
            ("connection", "Keep-Alive");
            ("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            (true);
            (true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(());
            // 发送请求参数
            (param);
            // flush输出流的缓冲
            ();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(()));
            String line;
            while ((line = ()) != null) {
                result += line;
            }
        } catch (Exception e) {
            ("发送 POST 请求出现异常!"+e);
            ();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    ();
                }
                if(in!=null){
                    ();
                }
            }
            catch(IOException ex){
                ();
            }
        }
        return result;
    }
}