SpringBoot使用RestTemplate发送带header的get请求

SpringBoot使用RestTemplate发送带header的get请求

创建RestTemplate配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author ***
 * @date 2022-03-21
 */
@Configuration
class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //设置连接超时
        factory.setConnectTimeout(15000);
        //设置读取超时
        factory.setReadTimeout(5000);
        return factory;
    }
}

发送get请求

		HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", authToken);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        Map<String,Object> map=new HashMap<>(16);
        map.put("pageNum",1);
        map.put("pageSize",999);
        map.put("productid",productid);
        if (!map.isEmpty()) {
            for (Map.Entry<String, Object> e : map.entrySet()) {
                builder.queryParam(e.getKey(), e.getValue());
            }
            // 在此处拼接真实请求地址  "?pageNo=1&pageSize=999&productid=productid"
            String realUrl = builder.build().toString(); 
            log.info("realUrl:{}", realUrl);
            HttpEntity<JSONObject> httpEntity = new HttpEntity<>(null, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(realUrl, HttpMethod.GET, httpEntity, String.class, map);
            log.info("返回结果:{}", exchange.getBody());
            String body = exchange.getBody();
            Map<String,Map<String,Map>> mapbody = JSON.parseObject(body, Map.class);
            Map<String,Map> data = mapbody.get("data");
            //将拿到的数据返回
            return R.ok(data);
        }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值