使用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í)例詳解的相關(guān)資料,需要的朋友可以參考下2017-05-05
SpringBoot全局異常處理機(jī)制和配置攔截器方式
這篇文章主要介紹了SpringBoot全局異常處理機(jī)制和配置攔截器方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
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的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
Springboot中LocalDateTime對象返回給前端格式化解決方案
在項(xiàng)目開發(fā)當(dāng)中前后端使用什么樣的時(shí)間格式,是一個(gè)值得關(guān)注的問題,這篇文章主要給大家介紹了關(guān)于Springboot中LocalDateTime對象返回給前端格式化的解決方案,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-04-04
Springboot web項(xiàng)目打包實(shí)現(xiàn)過程解析
這篇文章主要介紹了Springboot web項(xiàng)目打包實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08

