欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

spring boot RestTemplate 發(fā)送get請求的踩坑及解決

 更新時(shí)間:2021年08月19日 14:22:57   作者:從不喝茶  
這篇文章主要介紹了spring boot RestTemplate 發(fā)送get請求的踩坑及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

spring boot RestTemplate 發(fā)送get請求踩坑

閑話少說,代碼說話

RestTemplate 實(shí)例

手動實(shí)例化,這個(gè)我基本不用

RestTemplate restTemplate = new RestTemplate(); 

依賴注入,通常情況下我使用 java.net 包下的類構(gòu)建的 SimpleClientHttpRequestFactory

@Configuration
public class RestConfiguration {
    @Bean
    @ConditionalOnMissingBean({RestOperations.class, RestTemplate.class})
    public RestOperations restOperations() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(5000);
        requestFactory.setConnectTimeout(5000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        // 使用 utf-8 編碼集的 conver 替換默認(rèn)的 conver(默認(rèn)的 string conver 的編碼集為 "ISO-8859-1")
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
        while (iterator.hasNext()) {
            HttpMessageConverter<?> converter = iterator.next();
            if (converter instanceof StringHttpMessageConverter) {
                iterator.remove();
            }
        }
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }
}

請求地址

get 請求 url 為

http://localhost:8080/test/sendSms?phone=手機(jī)號&msg=短信內(nèi)容

錯(cuò)誤使用

@Autowired
private RestOperations restOperations;
public void test() throws Exception{
    String url = "http://localhost:8080/test/sendSms";
    Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("phone", "151xxxxxxxx");
    uriVariables.put("msg", "測試短信內(nèi)容");
    String result = restOperations.getForObject(url, String.class, uriVariables);
}

服務(wù)器接收的時(shí)候你會發(fā)現(xiàn),接收的該請求時(shí)沒有參數(shù)的

正確使用

@Autowired
private RestOperations restOperations;
public void test() throws Exception{
    String url = "http://localhost:8080/test/sendSms?phone={phone}&msg={phone}";
    Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("phone", "151xxxxxxxx");
    uriVariables.put("msg", "測試短信內(nèi)容");
    String result = restOperations.getForObject(url, String.class, uriVariables);
}

等價(jià)于

@Autowired
private RestOperations restOperations;
public void test() throws Exception{
    String url = "http://localhost:8080/test/sendSms?phone={phone}&msg={phone}";
    String result = restOperations.getForObject(url, String.class,  "151xxxxxxxx", "測試短信內(nèi)容");
}

springboot restTemplate訪問get,post請求的各種方式

springboot中封裝好了訪問外部請求的方法類,那就是RestTemplate。下面就簡單介紹一下,RestTemplate訪問外部請求的方法。

get請求

首先get請求的參數(shù)是拼接在url后面的。所以不需要額外添加參數(shù)。但是也需要分兩種情況。

1、 有請求頭

由于 getForEntity() 和 getForObject() 都無法加入請求頭。所以需要請求頭的連接只能使用 exchange() 來訪問。代碼如下

public JSONObject test(){
        try {
            RestTemplate re = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            String url = "http://test.api.com?id=123";
            headers.set("Content-Type","application/json");
            HttpEntity<JSONObject> jsonObject= re.exchange(url, HttpMethod.GET,new HttpEntity<>(headers),JSONObject.class);
            log.info("返回:{}",jsonObject.getBody());
            return jsonObject.getBody();
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

2、 無請求頭

無需請求頭的可以用三個(gè)方法實(shí)現(xiàn)。getForEntity() 和 getForObject() 還有 exchange() 都可以實(shí)現(xiàn)。下面講前兩種用的比較多的。

getForEntity()

public JSONObject test(){
        try {
            RestTemplate re = new RestTemplate();
            String url = "http://api.help.bj.cn/apis/alarm/?id=101020100";
            HttpEntity<JSONObject> jsonObject= re.getForEntity(url,JSONObject.class);
            log.info("返回:{}",jsonObject.getBody());
            return jsonObject.getBody();
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

getForObject()

public JSONObject test(){
        try {
            RestTemplate re = new RestTemplate();
            String url = "http://api.help.bj.cn/apis/alarm/?id=101020100";
            JSONObject jsonObject= re.getForObject(url,JSONObject.class);
            log.info("返回:{}",jsonObject);
            return jsonObject;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

post請求

post請求也分幾種情況

1、參數(shù)在body的form-data里面

public static JSONObject test(){
        try {
            RestTemplate re = new RestTemplate();
            String url = "http://localhost:8101/test";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            MultiValueMap<String, Object> loginJson = new LinkedMultiValueMap<>();
            loginJson.add("id", "123");
            JSONObject jsonObject= re.postForObject(url,new HttpEntity<>(loginJson,headers),JSONObject.class);
            log.info("返回:{}",jsonObject);
            return jsonObject;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

還可以把 postForObject 換成 postForEntity

2、參數(shù)在body的x-www-from-urlencodeed里面

只需要把請求頭的setContentType改成下面即可

headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
public static JSONObject test(){
        try {
            RestTemplate re = new RestTemplate();
            String url = "http://localhost:8101/test";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, Object> loginJson = new LinkedMultiValueMap<>();
            loginJson.add("id", "123");
            JSONObject jsonObject= re.postForObject(url,new HttpEntity<>(loginJson,headers),JSONObject.class);
            log.info("返回:{}",jsonObject);
            return jsonObject;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

3、參數(shù)在body的raw里面

在這里插入圖片描述

 public static JSONObject test(){
        try {
            RestTemplate re = new RestTemplate();
            String url = "http://localhost:8101/test";
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type","application/json");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id","1");
            JSONObject jsonObject1 = restTemplate
                    .postForObject(url,new HttpEntity<>(jsonObject,headers),JSONObject.class);
            log.info("返回:{}",jsonObject1);
            return jsonObject;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 解決springboot的findOne方法沒有合適的參數(shù)使用問題

    解決springboot的findOne方法沒有合適的參數(shù)使用問題

    這篇文章主要介紹了解決springboot的findOne方法沒有合適的參數(shù)使用問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • IntelliJ IDEA中使用mybatis-generator的示例

    IntelliJ IDEA中使用mybatis-generator的示例

    這篇文章主要介紹了IntelliJ IDEA中使用mybatis-generator,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-04-04
  • springboot+vue實(shí)現(xiàn)頁面下載文件

    springboot+vue實(shí)現(xiàn)頁面下載文件

    這篇文章主要為大家詳細(xì)介紹了springboot+vue實(shí)現(xiàn)頁面下載文件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-12-12
  • java繼承學(xué)習(xí)之super的用法解析

    java繼承學(xué)習(xí)之super的用法解析

    本文介紹java繼承super的用法,Java繼承是會用已存在的類的定義作為基礎(chǔ)建立新類的技術(shù)新類的定義可以增加新的數(shù)據(jù)或者新的功能,也可以使用父類的功能,但不能選擇性的繼承父類 這種繼承使得復(fù)用以前的代碼非常容易,能夠大大的縮短開發(fā)的周期,需要的朋友可以參考下
    2022-02-02
  • 全面解析Java main方法

    全面解析Java main方法

    main方法是我們學(xué)習(xí)Java語言學(xué)習(xí)的第一個(gè)方法,也是每個(gè)java使用者最熟悉的方法,每個(gè)Java應(yīng)用程序都必須有且僅有一個(gè)main方法。這篇文章通過實(shí)例代碼給大家介紹java main方法的相關(guān)知識,感興趣的朋友跟隨腳本之家小編一起學(xué)習(xí)吧
    2018-05-05
  • Springboot POI導(dǎo)出Excel(瀏覽器)

    Springboot POI導(dǎo)出Excel(瀏覽器)

    這篇文章主要為大家詳細(xì)介紹了Springboot POI導(dǎo)出Excel,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-05-05
  • java 實(shí)現(xiàn)簡單圣誕樹的示例代碼(圣誕節(jié)快樂)

    java 實(shí)現(xiàn)簡單圣誕樹的示例代碼(圣誕節(jié)快樂)

    這篇文章主要介紹了java 實(shí)現(xiàn)簡單圣誕樹的示例代碼(圣誕節(jié)快樂),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • Netty分布式FastThreadLocal的set方法實(shí)現(xiàn)邏輯剖析

    Netty分布式FastThreadLocal的set方法實(shí)現(xiàn)邏輯剖析

    這篇文章主要為大家介紹了Netty分布式FastThreadLocal的set方法實(shí)現(xiàn)邏輯剖析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-03-03
  • java自定義注解驗(yàn)證手機(jī)格式的實(shí)現(xiàn)示例

    java自定義注解驗(yàn)證手機(jī)格式的實(shí)現(xiàn)示例

    這篇文章主要介紹了java自定義注解驗(yàn)證手機(jī)格式的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • Java后臺如何處理日期參數(shù)格式

    Java后臺如何處理日期參數(shù)格式

    這篇文章主要介紹了Java后臺如何處理日期參數(shù)格式問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07

最新評論