当前位置: 代码网 > it编程>编程语言>Java > 使用Springboot封装好的发送post请求的工具类

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

2024年09月14日 Java 我要评论
springboot封装发送post请求工具类springboot封装好的发送http请求的工具类代码(最下面有普通的工具类): public static response sendpostreq

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;
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com