使用RestTemplate呼叫外部Http介面

2021-08-29 02:26:39 字數 1303 閱讀 9975

使用resttemplate呼叫外部http介面

我們使用resttemplate呼叫外部介面,resttemplate可以自動轉換實體類和json字串,這樣便於我們呼叫介面。

通常我們得到乙個外部介面,會告訴我們請求報文和響應報文。例如:

這樣在轉換時,就會自動將companyreqheader轉換為message_header,與json字串對應上。

接下來,我們就需要給實體類創造物件並且賦值,對於類中類的賦值,我們需要先給裡面的類賦值,再裡面的類作為屬性賦給外面的類。例如:

companyreqheader companyreqheader=new companyreqheader();

companyreqheader.setsyscode(「saic_tj_0002」);

companyreqheader.setauthcode(「c4b051f692eb4d0bbf15d9d008a727c0」);

companyreqheader.setbusinesstype(「005」);

companyreqheader.setsign(「tj」);

companyreqheader.setversion(「版本1」);

companyreqcontent companyreqcontent=new companyreqcontent();

companyreqcontent.setqrid(randomdto.getqrid());

companyreqcontent.setrettype(「1」);

companyreqcontent.setopertime("");

companyreq companyreq=new companyreq();

companyreq.setcompanyreqheader(companyreqheader);

companyreq.setcompanyreqcontent(companyreqcontent);

(companyreq類中包含了兩個類,companyreqheader和companyreqcontent)

建立好請求報文後,我們就可以使用resttemplate呼叫外部介面:

responseentity responseentity=resttemplate.postforentity(「

其中companyrsp為返回的響應報文的實體類,resttemplate為resttemplate的物件,postforentity方法有三個引數,分別為:外部介面位址、請求體的物件、返回的實體類。

如果單單這樣寫,你發現會報錯,這時需要加上:

RestTemplate使用總結

resttemplate的介紹就不說了,總的來說用這個物件可以很方便的模擬乙個http請求。talk is cheap,show me the code,使用的是springboot整合的工程所以以下涉及到的物件都是註解式的宣告和注入,一 宣告resttemplate物件 當然,可以利用註解 bea...

RestTemplate使用總結

resttemplate的介紹就不說了,總的來說用這個物件可以很方便的模擬乙個http請求。talk is cheap,show me the code,使用的是springboot整合的工程所以以下涉及到的物件都是註解式的宣告和注入,一 宣告resttemplate物件 當然,可以利用註解 bea...

使用restTemplate隨筆

使用resttemplate訪問其他介面時 採用post方式傳參 發現服務端接受不到引數 坑了半天 記錄一下 服務端是個servlet 以post接參 所以本地使用mvc模擬了一下 方便除錯 如下 客戶端 如下 test public void test1 不能以map或hashmap代替 否則服務...