使用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 所代表遠程資源的響應結(jié)果
*/
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("發(fā)送GET請求出現(xiàn)異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸入流
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ù)應該是 name1=value1&name2=value2 的形式。
* @return 所代表遠程資源的響應結(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();
// 設置通用的請求屬性
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請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發(fā)送請求參數(shù)
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("發(fā)送 POST 請求出現(xiàn)異常!"+e);
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring的BeanFactoryPostProcessor接口示例代碼詳解
這篇文章主要介紹了Spring的BeanFactoryPostProcessor接口,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02
使用SpringBoot實現(xiàn)Redis多數(shù)據(jù)庫緩存
在我的系統(tǒng)中,為了優(yōu)化用戶行為數(shù)據(jù)的存儲與訪問效率,我引入了Redis緩存,并將數(shù)據(jù)分布在不同的Redis數(shù)據(jù)庫中,通過這種方式,可以減少單一數(shù)據(jù)庫的負載,提高系統(tǒng)的整體性能,所以本文給大家介紹了使用SpringBoot實現(xiàn)Redis多數(shù)據(jù)庫緩存,需要的朋友可以參考下2024-06-06
SpringCloud項目集成Feign、Hystrix過程解析
這篇文章主要介紹了SpringCloud項目集成Feign、Hystrix過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11
mybatis plus generator 根據(jù)數(shù)據(jù)庫自動生成實體類的實現(xiàn)示例
本文主要介紹了mybatis plus generator 根據(jù)數(shù)據(jù)庫自動生成實體類的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
Spring Controller接收前端JSON數(shù)據(jù)請求方式
這篇文章主要為大家介紹了Spring Controller接收前端JSON數(shù)據(jù)請求方式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
2023-07-07 
