欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2024年09月14日 10:52:43   作者:Peter447  
本文介紹了在Springboot中封裝發(fā)送HTTP請求的工具類,并提供了普通的HTTP請求工具類代碼和Response類的使用示例,這些工具類可為開發(fā)者提供便利性和參考價值,幫助提高開發(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ù)合成一個請求
            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();
        }

再附帶一個我使用的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)");
            // 建立實際的連接
            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é)

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

相關(guān)文章

  • Java中HashMap獲取值的幾種方式匯總

    Java中HashMap獲取值的幾種方式匯總

    這篇文章主要介紹了Java中HashMap獲取值的幾種方式匯總,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Spring Controller接收前端JSON數(shù)據(jù)請求方式

    Spring Controller接收前端JSON數(shù)據(jù)請求方式

    這篇文章主要為大家介紹了Spring Controller接收前端JSON數(shù)據(jù)請求方式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-07-07
  • 最新評論