RestTemplate是Spring提供的一個基于restful風(fēng)格的http調(diào)用的API寥粹,使用簡單签夭、方便,讓我們擺脫了寫繁雜的HttpURLConnection代碼泪酱。本文記錄通過RestTemplate發(fā)起帶header的http請求拓轻。
1.配置RestTemplate
我們可以通過Java config模式簡單快速的配置RestTemplate,即利用注解@Configuration在配置類中聲明bean达吞,詳見如下代碼:
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
//添加RestTemplate的報文轉(zhuǎn)換器
restTemplate.getMessageConverters().add(this.getFastJsonConverter());
return restTemplate;
}
//自定義報文轉(zhuǎn)換器
FastJsonHttpMessageConverter getFastJsonConverter(){
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
// 設(shè)置feature
fastJsonConfig.setFeatures(Feature.AllowISO8601DateFormat);
// 設(shè)置日期格式搪桂、關(guān)閉循環(huán)引用檢測
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect);
//指定全局日期格式
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
//設(shè)定MediaType
fastJsonHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON,MediaType.APPLICATION_JSON_UTF8));
return fastJsonHttpMessageConverter;
}
}
2.發(fā)起帶header的http請求
配置好RestTemplate后我們就可以使用它發(fā)起http請求了撵术,這里我們演示帶請求頭的請求示例嫩与,詳見如下代碼(代碼中有詳細(xì)注釋):
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.*;
import java.util.stream.Collectors;
@Service
@Slf4j
public class FooService {
private static final String FOO_HEADER_NAME = "Foo";
private static final String TOKEN_HEADER_NAME = "AccessToken";
private static final int SUCCESS_CODE = 200;
@Autowired
private RestTemplate restTemplate;
public Map<String, ResultBO> getInfo(Set<String> argSet) {
if (CollectionUtils.isEmpty(argSet)) {
return Collections.emptyMap();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.add(DEPT_HEADER_NAME, "項目中配置的具體值");
headers.add(TOKEN_HEADER_NAME, "項目中配置的具體值");
RequestBody request = new RequestBody(StringUtils.join(argSet, ","));
log.info("request RequestBody: {}", request);
HttpEntity<RequestBody> requestParam = new HttpEntity<>(request, headers);
ResponseEntity<ResponseBody> responseEntity = restTemplate.postForEntity("urlAddress", requestParam, ResponseBody.class);
log.info("responseEntity: {}", JSON.toJSONString(responseEntity));
if (Objects.isNull(responseEntity)) {
throw new RuntimeException("查詢失敗, response is null");
}
if (SUCCESS_CODE != responseEntity.getStatusCodeValue()) {
throw new RuntimeException("查詢失敗, status: " + responseEntity.getStatusCodeValue());
}
ResponseBody responseBody = responseEntity.getBody();
if (Objects.isNull(responseBody)) {
log.info("responseEntity_body is null");
return Collections.emptyMap();
}
List<ResultBO> resultBOS = responseBody.getResult();
return resultBOS.stream().collect(Collectors.toMap(k -> String.valueOf(k.getId()), v -> v, (f,s) -> s));
}
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public static class RequestBody {
@ApiModelProperty("業(yè)務(wù)數(shù)據(jù)id 多個時逗號連接")
private String ids;
}
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public static class ResponseBody {
@ApiModelProperty("0成功")
private Integer code;
@ApiModelProperty("結(jié)果信息")
private List<ResultBO> result;
}
}
OK,回聊~