最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Springboot封裝好的發(fā)送post請求的工具類

 更新時(shí)間:2024年09月14日 10:52:43   作者:Peter447  
本文介紹了在Springboot中封裝發(fā)送HTTP請求的工具類,并提供了普通的HTTP請求工具類代碼和Response類的使用示例,這些工具類可為開發(fā)者提供便利性和參考價(jià)值,幫助提高開發(fā)效率

Springboot封裝發(fā)送post請求工具類

Springboot封裝好的發(fā)送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);
            //將請求頭部和參數(shù)合成一個(gè)請求
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
            //執(zhí)行HTTP請求,將返回的結(jié)構(gòu)使用Response類格式化
            ResponseEntity<Response> response = client.exchange(url, method, requestEntity, Response.class);
    
            return response.getBody();
        }

再附帶一個(gè)我使用的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 + '\'' +
                '}';
    }
}

普通的發(fā)送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發(fā)送GET方法的請求
     *
     * @param url
     *            發(fā)送請求的URL
     * @param
     * @return URL 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打開和URL之間的連接
            URLConnection connection = realUrl.openConnection();
            // 設(shè)置通用的請求屬性
            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)");
            // 建立實(shí)際的連接
            connection.connect();
            // 獲取所有響應(yīng)頭字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍歷所有的響應(yīng)頭字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定義 BufferedReader輸入流來讀取URL的響應(yīng)
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("發(fā)送GET請求出現(xiàn)異常!" + e);
            e.printStackTrace();
        }
        // 使用finally塊來關(guān)閉輸入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
 
    /**
     * 向指定 URL 發(fā)送POST方法的請求
     *
     * @param url
     *            發(fā)送請求的 URL
     * @param param
     *            請求參數(shù),請求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。
     * @return 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果
     */
    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();
            // 設(shè)置通用的請求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 發(fā)送POST請求必須設(shè)置如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 獲取URLConnection對象對應(yīng)的輸出流
            out = new PrintWriter(conn.getOutputStream());
            // 發(fā)送請求參數(shù)
            out.print(param);
            // flush輸出流的緩沖
            out.flush();
            // 定義BufferedReader輸入流來讀取URL的響應(yīng)
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("發(fā)送 POST 請求出現(xiàn)異常!"+e);
            e.printStackTrace();
        }
        //使用finally塊來關(guān)閉輸出流、輸入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
}

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • java枚舉類的構(gòu)造函數(shù)實(shí)例詳解

    java枚舉類的構(gòu)造函數(shù)實(shí)例詳解

    這篇文章主要介紹了java枚舉類的構(gòu)造函數(shù)實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-05-05
  • SpringBoot全局異常處理機(jī)制和配置攔截器方式

    SpringBoot全局異常處理機(jī)制和配置攔截器方式

    這篇文章主要介紹了SpringBoot全局異常處理機(jī)制和配置攔截器方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Java在Excel中添加水印的實(shí)現(xiàn)(單一水印、平鋪水印)

    Java在Excel中添加水印的實(shí)現(xiàn)(單一水印、平鋪水印)

    這篇文章主要介紹了Java在Excel中添加水印的實(shí)現(xiàn)(單一水印、平鋪水印),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • java判斷String類型是否能轉(zhuǎn)換為int的方法

    java判斷String類型是否能轉(zhuǎn)換為int的方法

    今天小編就為大家分享一篇java判斷String類型是否能轉(zhuǎn)換為int的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • SpringBoot文件上傳的原理解析

    SpringBoot文件上傳的原理解析

    這篇文章主要介紹了SpringBoot文件上傳的原理解析,SpringBoot 文件上傳是一種方便快捷的方式,可以將文件上傳到服務(wù)器,通過使用SpringBoot的文件上傳功能,可以輕松地實(shí)現(xiàn)文件上傳功能,需要的朋友可以參考下
    2023-10-10
  • Java浮點(diǎn)類數(shù)字運(yùn)算方式

    Java浮點(diǎn)類數(shù)字運(yùn)算方式

    在進(jìn)行浮點(diǎn)數(shù)的加減運(yùn)算時(shí),直接使用+和-可能會(huì)引入精度誤差,為了比較浮點(diǎn)數(shù),可以使用Double的compareTo()方法,或者通過定義一個(gè)容差值(Epsilon)來判斷兩個(gè)浮點(diǎn)數(shù)是否相等,此外,Double.compare()方法也能比較兩個(gè)double值
    2024-10-10
  • Mybatis中Mapper映射文件使用詳解

    Mybatis中Mapper映射文件使用詳解

    這篇文章主要介紹了Mybatis中Mapper映射文件使用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • Springboot中LocalDateTime對象返回給前端格式化解決方案

    Springboot中LocalDateTime對象返回給前端格式化解決方案

    在項(xiàng)目開發(fā)當(dāng)中前后端使用什么樣的時(shí)間格式,是一個(gè)值得關(guān)注的問題,這篇文章主要給大家介紹了關(guān)于Springboot中LocalDateTime對象返回給前端格式化的解決方案,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-04-04
  • Java手機(jī)號最新校驗(yàn)規(guī)則

    Java手機(jī)號最新校驗(yàn)規(guī)則

    在Java中,進(jìn)行手機(jī)號校驗(yàn)通常使用正則表達(dá)式(Regex)來匹配手機(jī)號的格式,以下是一個(gè)基于當(dāng)前(截至2024年)中國手機(jī)號規(guī)則的校驗(yàn)方法,感興趣的朋友跟隨小編一起看看吧
    2024-05-05
  • Springboot web項(xiàng)目打包實(shí)現(xiàn)過程解析

    Springboot web項(xiàng)目打包實(shí)現(xiàn)過程解析

    這篇文章主要介紹了Springboot web項(xiàng)目打包實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08

最新評論

遂溪县| 灵宝市| 旌德县| 类乌齐县| 界首市| 武安市| 建始县| 呼图壁县| 汶上县| 堆龙德庆县| 彰化县| 文昌市| 腾冲县| 花莲市| 无极县| 新乐市| 阿拉善盟| 澄迈县| 仁化县| 景泰县| 封丘县| 修水县| 庆云县| 灵石县| 黎平县| 龙山县| 土默特右旗| 睢宁县| 巫山县| 新乡县| 贡觉县| 苍溪县| 宁武县| 栖霞市| 和林格尔县| 修武县| 千阳县| 定结县| 军事| 武穴市| 桃园市|