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);
}