spring boot中 使用http請求

因為項目需求,需要兩個系統之間進行通信,經過一番調研,決定使用http請求。
服務端沒有什么好說的,本來就是使用web 頁面進行訪問的,所以spring boot啟動后,controller層的接口就自動暴露出來了,客戶端通過調用對應的url即可,所以這里主要就客戶端。
首先我自定義了一個用來處理http 請求的工具類DeviceFactoryHttp,
既然是url訪問,那就有兩個問題需要處理,一個請求服務的url,和請求服務端的參數,客戶端的消息頭
請求服務的url:請求服務端url我定義的是跟客戶端一個樣的url
服務端的參數:服務端的參數有兩種一種經過封裝的,類似下面這樣:
http://localhost:8080/switch/getAllStatus?data{"interface name”:”getAllStudentStaus”}
一種是沒有經過封裝的,類似下面這樣:
http://localhost:8080/switch/getStudentInfoByName?name=zhangSan
首先是經過封裝:
一:初始化httpclient
private static HttpClient client = null;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(128);
cm.setDefaultMaxPerRoute(128);
client = HttpClients.custom().setConnectionManager(cm).build();
}
二:獲取請求的url,因為我服務端定義的url與客戶端一樣,所以我直接使用請求客戶端的url
//根據request獲取請求的url
public? StringBuffer getUrlToRequest(HttpServletRequest request) {
StringBuffer url=request.getRequestURL();//獲取請求的url(http://localhost:8080/switch/getStudentInfoByName)
String[] splitArr=url.toString().split("/");
String appName=splitArr[3];//項目名稱
String ipReport=splitArr[2];//項目ip:report
String resultStr=url.toString().replaceAll(appName,DevFacConstans.facname).replaceAll(ipReport, DevFacConstans.ip+":"+DevFacConstans.report);
return new StringBuffer(resultStr);
}
獲取url根據/ 進行split,因為我這是測試環境,生產環境ip,端口號(域名)肯定不是localhost,有的前面還會加上項目名稱,
所以我split對應的值來進行替換。
三:拼裝請求參數,調用http請求
/**
* 發送http請求 有request
* 給controller層調用
* @param request
* @return
*/
public String sendHttpToDevFac(HttpServletRequest request)throws Exception {
HttpClient client = null;
String returnResult="";
// http://localhost:8080/leo/1.0/h5/login
StringBuffer urlBuffer=getUrlToRequest(request);//調用第二步,獲取url
//獲取參數并拼裝
String dataAsJson = request.getParameter("data");
String encoderData=URLEncoder.encode(dataAsJson,"utf-8");
HttpGet get=new HttpGet(urlBuffer.append("?data=").append(encoderData).toString());
//set headers
Enumeration<String> headerNames=request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName=headerNames.nextElement();
String headerValue=request.getHeader(headerName);
get.setHeader(headerName, headerValue);
}
client=DeviceFactoryHttp.client;
logger.info("開始調用http請求,請求url:"+urlBuffer.toString());
HttpResponse rep=client.execute(get);
returnResult=EntityUtils.toString(rep.getEntity(),"utf-8");
logger.info("http 請求調用結束!!");
return returnResult;
}
先獲取請求的參數,再將參數拼裝在url后面,URLEncoder.encode?這個不要忘了,因為參數會有一些符號,需要對參數進行編碼后再加入url,否則就會拋出異常,
set headers:因為有部分信息服務端會從請求頭中取出,所以我將客戶端的請求頭也set到服務端的request中,請求的url和請求的參數拼好就就可以client.exceute(get)執行請求了。
上面的是我瀏覽器直接將request請求作為參數傳到我客戶端,我所以我可以直接從request中獲取url,有的是沒有request,就需要從request的上下文環境中取了。
沒有經過封裝的:
首先從上下文中獲取request的
/**
* 獲取request
* @return
*/
public static HttpServletRequest getRequest(){
? ServletRequestAttributes ra= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
? HttpServletRequest request =? ra.getRequest();
? return request;
}
二:有了request后,就有了url,下面再來解析請求參數,因為這個參數是沒有封裝的,所以獲取所有的請求參數
/*** 沒有request 請求,給controller層調用* @param key* @param interfaceName* @param strings* @return* @throws Exception*/public String centerToDeviceFacNoRequest(String key,String interfaceName)throws Exception {try {HttpServletRequest request=getRequest();//上面第一步,從上下文中獲取url//獲取reuquest請求參數Enumeration<String> names=  request.getParameterNames();Map<String,String>paramMap=new HashMap<>();//遍歷請求mapwhile(names.hasMoreElements()) {String name=names.nextElement();String value=(String) request.getParameter(name);paramMap.put(name, value);}//調用發送http請求的方法return sendHttpToDevFacNoData(paramMap,request);} catch (Exception e) {e.printStackTrace();}//endreturn null;}

?

三:發送http請求
/*** 發送http請求,【沒有data數據的】* @return*/public String sendHttpToDevFacNoData(Map<String,String>paramMap,HttpServletRequest request)throws Exception {HttpClient client = null;String result="";StringBuffer dataBuffer=getUrlToRequest(request);//獲取urldataBuffer.append("?");client=DeviceFactoryHttp.client;Iterator<Entry<String, String>> paamIt=paramMap.entrySet().iterator();while(paamIt.hasNext()) {Entry<String, String> entry=paamIt.next();dataBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");}String resultUrl=dataBuffer.toString().substring(0, dataBuffer.toString().lastIndexOf("&"));//發送請求HttpGet get=new HttpGet(resultUrl);//set headersEnumeration<String> headerNames=request.getHeaderNames();while(headerNames.hasMoreElements()) {String headerName=headerNames.nextElement();String headerValue=request.getHeader(headerName);get.setHeader(headerName, headerValue);}HttpResponse rep=client.execute(get);logger.info("開始調用http請求,請求url:"+resultUrl);//返回結果result=EntityUtils.toString(rep.getEntity(),"utf-8");logger.info(" http 請求調用結束!!");return result;}

?

轉載于:https://www.cnblogs.com/zhangXingSheng/p/7745009.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390982.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390982.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390982.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

arduino joy_如何用Joy開發Kubernetes應用

arduino joyLet’s face it: Developing distributed applications is painful.讓我們面對現實&#xff1a;開發分布式應用程序很痛苦。 Microservice architectures might be great for decoupling and scalability but they are intimidatingly complex when it comes to de…

怎么樣得到平臺相關的換行符?

問題&#xff1a;怎么樣得到平臺相關的換行符&#xff1f; Java里面怎么樣得到平臺相關的換行符。我不可能到處都用"\n" 回答一 In addition to the line.separator property, if you are using java 1.5 or later and the String.format (or other formatting me…

scrapy常用工具備忘

scrapy常用的命令分為全局和項目兩種命令&#xff0c;全局命令就是不需要依靠scrapy項目&#xff0c;可以在全局環境下運行&#xff0c;而項目命令需要在scrapy項目里才能運行。一、全局命令##使用scrapy -h可以看到常用的全局命令 [rootaliyun ~]# scrapy -h Scrapy 1.5.0 - n…

機器學習模型 非線性模型_機器學習:通過預測菲亞特500的價格來觀察線性模型的工作原理...

機器學習模型 非線性模型Introduction介紹 In this article, I’d like to speak about linear models by introducing you to a real project that I made. The project that you can find in my Github consists of predicting the prices of fiat 500.在本文中&#xff0c;…

NOIP賽前模擬20171027總結

題目&#xff1a; 1.壽司 給定一個環形的RB串要求經過兩兩互換后RB分別形成兩段連續區域,求最少操作次數(算法時間O(n)) 2.金字塔 給定一個金字塔的側面圖有n層已知每一層的寬度高度均為1要求在圖中取出恰好K個互不相交的矩形&#xff08;邊緣可以重疊&#xff09;,求最多可以取…

虛幻引擎 js開發游戲_通過編碼3游戲學習虛幻引擎4-5小時免費游戲開發視頻課程

虛幻引擎 js開發游戲One of the most widely used game engines is Unreal Engine by Epic Games. On the freeCodeCamp.org YouTube channel, weve published a comprehensive course on how to use Unreal Engine with C to develop games.Epic Games的虛幻引擎是使用最廣泛的…

建造者模式什么時候使用?

問題&#xff1a;建造者模式什么時候使用&#xff1f; 建造者模式在現實世界里面的使用例子是什么&#xff1f;它有啥用呢&#xff1f;為啥不直接用工廠模式 回答一 下面是使用這個模式的一些理由和Java的樣例代碼&#xff0c;但是它是由設計模式的4個人討論出來的建造者模式…

TP5_學習

2017.10.27&#xff1a;1.index入口跑到public下面去了 2.不能使用 define(BIND_MODULE,Admin);自動生成模塊了&#xff0c;網上查了下&#xff1a; \think\Build::module(Admin);//親測,可用 2017.10.28:1.一直不知道怎么做查詢顯示和全部顯示&#xff0c;原來如此簡單&#x…

sql sum語句_SQL Sum語句示例說明

sql sum語句SQL中的Sum語句是什么&#xff1f; (What is the Sum statement in SQL?) This is one of the aggregate functions (as is count, average, max, min, etc.). They are used in a GROUP BY clause as it aggregates data presented by the SELECT FROM WHERE port…

10款中小企業必備的開源免費安全工具

10款中小企業必備的開源免費安全工具 secist2017-05-188共527453人圍觀 &#xff0c;發現 7 個不明物體企業安全工具很多企業特別是一些中小型企業在日常生產中&#xff0c;時常會因為時間、預算、人員配比等問題&#xff0c;而大大減少或降低在安全方面的投入。這時候&#xf…

為什么Java里面沒有 SortedList

問題&#xff1a;為什么Java里面沒有 SortedList Java 里面有SortedSet和SortedMap接口&#xff0c;它們都屬于Java的集合框架和提供對元素進行排序的方法 然鵝&#xff0c;在我的認知里Java就沒有SortedList這個東西。你只能使用java.util.Collections.sort()去排序一個list…

圖片主成分分析后的可視化_主成分分析-可視化

圖片主成分分析后的可視化If you have ever taken an online course on Machine Learning, you must have come across Principal Component Analysis for dimensionality reduction, or in simple terms, for compression of data. Guess what, I had taken such courses too …

回溯算法和遞歸算法_回溯算法:遞歸和搜索示例說明

回溯算法和遞歸算法Examples where backtracking can be used to solve puzzles or problems include:回溯可用于解決難題或問題的示例包括&#xff1a; Puzzles such as eight queens puzzle, crosswords, verbal arithmetic, Sudoku [nb 1], and Peg Solitaire. 諸如八個皇后…

C#中的equals()和==

using System;namespace EqualsTest {class EqualsTest{static void Main(string[] args){//值類型int x 1;int y 1;Console.WriteLine(x y);//TrueConsole.WriteLine(x.Equals(y));//True //引用類型A a new A();B b new B();//Console.WriteLine(ab);//報錯…

JPA JoinColumn vs mappedBy

問題&#xff1a;JPA JoinColumn vs mappedBy 兩者的區別是什么呢 Entity public class Company {OneToMany(cascade CascadeType.ALL , fetch FetchType.LAZY)JoinColumn(name "companyIdRef", referencedColumnName "companyId")private List<B…

TP引用樣式表和js文件及驗證碼

TP引用樣式表和js文件及驗證碼 引入樣式表和js文件 <script src"__PUBLIC__/bootstrap/js/jquery-1.11.2.min.js"></script> <script src"__PUBLIC__/bootstrap/js/bootstrap.min.js"></script> <link href"__PUBLIC__/bo…

pytorch深度學習_深度學習和PyTorch的推薦系統實施

pytorch深度學習The recommendation is a simple algorithm that works on the principle of data filtering. The algorithm finds a pattern between two users and recommends or provides additional relevant information to a user in choosing a product or services.該…

什么是JavaScript中的回調函數?

This article gives a brief introduction to the concept and usage of callback functions in the JavaScript programming language.本文簡要介紹了JavaScript編程語言中的回調函數的概念和用法。 函數就是對象 (Functions are Objects) The first thing we need to know i…

Java 集合-集合介紹

2017-10-30 00:01:09 一、Java集合的類關系圖 二、集合類的概述 集合類出現的原因&#xff1a;面向對象語言對事物的體現都是以對象的形式&#xff0c;所以為了方便對多個對象的操作&#xff0c;Java就提供了集合類。數組和集合類同是容器&#xff0c;有什么不同&#xff1a;數…

為什么Java不允許super.super.method();

問題&#xff1a;為什么Java不允許super.super.method(); 我想出了這個問題&#xff0c;認為這個是很好解決的&#xff08;也不是沒有它就不行的&#xff09;如果可以像下面那樣寫的話&#xff1a; Override public String toString() {return super.super.toString(); }我不…