使用RestTemplate發起Http請求

2021-08-20 11:46:53 字數 1131 閱讀 8184

這裡主要記錄一下get請求和post請求的使用。

首先,看一下啊resttemplate的原始碼方法:

可以看到兩種請求得方法大同小異。xxforentity返回的是responseentity型別的資料,其中包含了頭資訊和返回內容。而xxforobject返回的是約定好的乙個型別,其中只有返回的內容資訊。

postforlocation返回了乙個uri物件,這個指的是新資源的位址。

下面來看看具體的**:

resttemplate resttemplate =

new resttemplate();

// 無參

responseentity<

string

> responseentity1 =

.class);

// 多引數

responseentity<

string

> responseentity2 =

.class, "1", "2");

map<

string, object>

map=

new hashmap<>();

map.put("m", "你好");

map.put("n", 111);

// map引數

responseentity<

string

> responseentity3 =

.class, map);

上面的**演示了get請求的xxforentity的三種方式。其實看原始碼可以發現,這些方法都很類似,很容易理解。其中需要注意的是傳參的方式,比如第二種多引數的形式,在url位址中用數字指代引數,比如n=表示後面多引數的第乙個引數。而map引數則用key代替。

除了get,post請求,resttemplate還定義了delete,put等請求的方法。也可以直接使用exchange方法,只需要用httpmethod列舉類來指定具體的請求型別就行了。

相對於httpclient的方式,resttemplate確實簡單了許多。其提供的功能也很全面。有興趣的可以看看原始碼。

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代替 否則服務...