RestTemplate是Spring提供的一个基于restful风格的http调用的API,使用简单、方便,让我们摆脱了写繁杂的HttpURLConnection代码。本文记录通过RestTemplate发起带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的报文转换器
restTemplate.getMessageConverters().add(this.getFastJsonConverter());
return restTemplate;
}
//自定义报文转换器
FastJsonHttpMessageConverter getFastJsonConverter(){
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
// 设置feature
fastJsonConfig.setFeatures(Feature.AllowISO8601DateFormat);
// 设置日期格式、关闭循环引用检测
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.DisableCircularReferenceDetect);
//指定全局日期格式
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
//设定MediaType
fastJsonHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON,MediaType.APPLICATION_JSON_UTF8));
return fastJsonHttpMessageConverter;
}
}
2.发起带header的http请求
配置好RestTemplate后我们就可以使用它发起http请求了,这里我们演示带请求头的请求示例,详见如下代码(代码中有详细注释):
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("业务数据id 多个时逗号连接")
private String ids;
}
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public static class ResponseBody {
@ApiModelProperty("0成功")
private Integer code;
@ApiModelProperty("结果信息")
private List<ResultBO> result;
}
}
OK,回聊~