最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

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

閑話少說(shuō),代碼說(shuō)話

RestTemplate 實(shí)例

手動(dòng)實(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;
    }
}

請(qǐng)求地址

get 請(qǐng)求 url 為

http://localhost:8080/test/sendSms?phone=手機(jī)號(hào)&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", "測(cè)試短信內(nèi)容");
    String result = restOperations.getForObject(url, String.class, uriVariables);
}

服務(wù)器接收的時(shí)候你會(huì)發(fā)現(xiàn),接收的該請(qǐng)求時(shí)沒(méi)有參數(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", "測(cè)試短信內(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", "測(cè)試短信內(nèi)容");
}

springboot restTemplate訪問(wèn)get,post請(qǐng)求的各種方式

springboot中封裝好了訪問(wèn)外部請(qǐng)求的方法類,那就是RestTemplate。下面就簡(jiǎn)單介紹一下,RestTemplate訪問(wèn)外部請(qǐng)求的方法。

get請(qǐng)求

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

1、 有請(qǐng)求頭

由于 getForEntity() 和 getForObject() 都無(wú)法加入請(qǐng)求頭。所以需要請(qǐng)求頭的連接只能使用 exchange() 來(lái)訪問(wèn)。代碼如下

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、 無(wú)請(qǐng)求頭

無(wú)需請(qǐng)求頭的可以用三個(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請(qǐng)求

post請(qǐng)求也分幾種情況

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里面

只需要把請(qǐng)求頭的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)文章

  • kafka的消息存儲(chǔ)機(jī)制和原理分析

    kafka的消息存儲(chǔ)機(jī)制和原理分析

    這篇文章主要介紹了kafka的消息存儲(chǔ)機(jī)制和原理,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • SpringBoot項(xiàng)目部署到騰訊云的實(shí)現(xiàn)步驟

    SpringBoot項(xiàng)目部署到騰訊云的實(shí)現(xiàn)步驟

    本文主要介紹了SpringBoot項(xiàng)目部署到騰訊云的實(shí)現(xiàn)步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • java讀取xml配置參數(shù)代碼實(shí)例

    java讀取xml配置參數(shù)代碼實(shí)例

    這篇文章主要介紹了java讀取xml配置參數(shù)代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • dom4j從jar包中讀取xml文件的方法

    dom4j從jar包中讀取xml文件的方法

    這篇文章主要介紹了dom4j從jar包中讀取xml文件的方法,需要的朋友可以參考下
    2014-02-02
  • SpringBoot 下的 Static 文件夾打包成前端資源的示例代碼

    SpringBoot 下的 Static 文件夾打包成前端資源的示例代碼

    這篇文章主要介紹了SpringBoot 下的 Static 文件夾如何打包成前端資源,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-06-06
  • Java集合框架超詳細(xì)小結(jié)

    Java集合框架超詳細(xì)小結(jié)

    Java中提供的一種容器,可以用來(lái)存儲(chǔ)多個(gè)數(shù)據(jù)。java集合大致可以分為Set,List,Queue和Map四種體系。這篇文章主要介紹了Java集合框架超詳細(xì)小結(jié),需要的朋友可以參考下
    2021-08-08
  • java8 實(shí)現(xiàn)提取集合對(duì)象的每個(gè)屬性

    java8 實(shí)現(xiàn)提取集合對(duì)象的每個(gè)屬性

    這篇文章主要介紹了java8 實(shí)現(xiàn)提取集合對(duì)象的每個(gè)屬性方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-02-02
  • idea聚合工程搭建過(guò)程詳解

    idea聚合工程搭建過(guò)程詳解

    本章主要以order訂單服務(wù)來(lái)遠(yuǎn)程調(diào)用payment支付服務(wù)為例,當(dāng)然這里只是簡(jiǎn)單的一個(gè)遠(yuǎn)程調(diào)用,沒(méi)有太復(fù)雜的邏輯,重點(diǎn)是要掌握的是maven的聚合工程搭建,微服務(wù)分模塊的思想,每一個(gè)步驟我都會(huì)詳細(xì)記錄,并且文章下方還提供了git源碼地址
    2022-06-06
  • java接口語(yǔ)法以及與類的關(guān)系詳解

    java接口語(yǔ)法以及與類的關(guān)系詳解

    接口在JAVA編程語(yǔ)言中是一個(gè)抽象類型,是抽象方法的集合,接口通常以interface來(lái)聲明。一個(gè)類通過(guò)繼承接口的方式,從而來(lái)繼承接口的抽象方法
    2021-10-10
  • SpringBoot?模板模式實(shí)現(xiàn)優(yōu)惠券邏輯的示例代碼

    SpringBoot?模板模式實(shí)現(xiàn)優(yōu)惠券邏輯的示例代碼

    這篇文章主要介紹了SpringBoot?模板模式實(shí)現(xiàn)優(yōu)惠券邏輯,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-08-08

最新評(píng)論

拉孜县| 洪泽县| 墨竹工卡县| 奇台县| 安阳市| 庐江县| 霸州市| 平泉县| 邹城市| 偏关县| 宜兰县| 南川市| 抚州市| 博客| 英吉沙县| 恩施市| 苍梧县| 武乡县| 淮阳县| 富民县| 海宁市| 彭山县| 台北县| 道孚县| 丹凤县| 赣州市| 梁山县| 鹤岗市| 黄冈市| 邛崃市| 弥勒县| 雅江县| 潜江市| 南投县| 团风县| 新营市| 峨山| 高淳县| 兴和县| 甘南县| 揭东县|