使用Springboot封裝好的發(fā)送post請(qǐng)求的工具類
Springboot封裝發(fā)送post請(qǐng)求工具類
Springboot封裝好的發(fā)送http請(qǐng)求的工具類代碼
(最下面有普通的工具類):
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); //將請(qǐng)求頭部和參數(shù)合成一個(gè)請(qǐng)求 HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers); //執(zhí)行HTTP請(qǐng)求,將返回的結(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請(qǐng)求的工具類
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方法的請(qǐng)求 * * @param url * 發(fā)送請(qǐng)求的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); // 打開(kāi)和URL之間的連接 URLConnection connection = realUrl.openConnection(); // 設(shè)置通用的請(qǐng)求屬性 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輸入流來(lái)讀取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請(qǐng)求出現(xiàn)異常!" + e); e.printStackTrace(); } // 使用finally塊來(lái)關(guān)閉輸入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 發(fā)送POST方法的請(qǐng)求 * * @param url * 發(fā)送請(qǐng)求的 URL * @param param * 請(qǐng)求參數(shù),請(qǐng)求參數(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); // 打開(kāi)和URL之間的連接 URLConnection conn = realUrl.openConnection(); // 設(shè)置通用的請(qǐng)求屬性 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請(qǐng)求必須設(shè)置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對(duì)象對(duì)應(yīng)的輸出流 out = new PrintWriter(conn.getOutputStream()); // 發(fā)送請(qǐng)求參數(shù) out.print(param); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來(lái)讀取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 請(qǐng)求出現(xiàn)異常!"+e); e.printStackTrace(); } //使用finally塊來(lái)關(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)文章
簡(jiǎn)單解析execute和submit有什么區(qū)別
這篇文章主要介紹了簡(jiǎn)單解析execute和submit有什么區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11Spring的BeanFactoryPostProcessor接口示例代碼詳解
這篇文章主要介紹了Spring的BeanFactoryPostProcessor接口,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02使用SpringBoot實(shí)現(xiàn)Redis多數(shù)據(jù)庫(kù)緩存
在我的系統(tǒng)中,為了優(yōu)化用戶行為數(shù)據(jù)的存儲(chǔ)與訪問(wèn)效率,我引入了Redis緩存,并將數(shù)據(jù)分布在不同的Redis數(shù)據(jù)庫(kù)中,通過(guò)這種方式,可以減少單一數(shù)據(jù)庫(kù)的負(fù)載,提高系統(tǒng)的整體性能,所以本文給大家介紹了使用SpringBoot實(shí)現(xiàn)Redis多數(shù)據(jù)庫(kù)緩存,需要的朋友可以參考下2024-06-06SpringCloud項(xiàng)目集成Feign、Hystrix過(guò)程解析
這篇文章主要介紹了SpringCloud項(xiàng)目集成Feign、Hystrix過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11mybatis plus generator 根據(jù)數(shù)據(jù)庫(kù)自動(dòng)生成實(shí)體類的實(shí)現(xiàn)示例
本文主要介紹了mybatis plus generator 根據(jù)數(shù)據(jù)庫(kù)自動(dòng)生成實(shí)體類的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09SpringBoot通過(guò)AOP與注解實(shí)現(xiàn)入?yún)⑿r?yàn)詳情
這篇文章主要介紹了SpringBoot通過(guò)AOP與注解實(shí)現(xiàn)入?yún)⑿r?yàn)詳情,文章從相關(guān)問(wèn)題展開(kāi)全文內(nèi)容詳情,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-05-05Spring Controller接收前端JSON數(shù)據(jù)請(qǐng)求方式
這篇文章主要為大家介紹了Spring Controller接收前端JSON數(shù)據(jù)請(qǐng)求方式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07