开发者

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

开发者 https://www.devze.com 2024-09-15 10:19 出处:网络 作者: Peter447
目录Springboot封装发送post请求工具类Springboot封装好的发送http请求的工具类代码再附带一个我使用的Response类普通的发送http请求的工具类总结Springboot封装发送post请求工具类
目录
  • Springboot封装发送post请求工具类
    • Springboot封装好的发送http请求的工具类代码
    • 再附带一个我使用的Response类
    • 普通的发送http请求的工具类
  • 总结

    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
     */
    pandroidublic 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 S编程客栈tring sendGet(String upythonrl) {
            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;
        }
    }
    

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

    0

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    关注公众号