Rest风格网站
Rest风格要求URL中不能存在动词,一个URL对应一种资源名,请求方式GET、POST、DELETE、PUT是对这种资源的操作。
Spring mvc支持REST风格的注解:
- @RestController表示期望控制器采用REST风格
- @GetMapping、@PostMapping、@DeleteMapping等,都是REST风格的注解
- @ResponseStatus(HttpStatus.CREATED)主要作用就是为了改变Http响应的状态码
http请求客户端工具包
工具包有:
- Spring RestTemplate:spring自带的
- Okhttp3:当前主流的网络请求开源框架,支持HTTP2/SPDY协议、支持自动重连、自动维护的socket连接池等
- Apache HttpClient:性能不是太好
- HttpUrlConnection:API封装的不是太好
RestTemplate的使用
RestTemplate作为客户端向Rest服务发送请求,服务间调用采用REST风格。Spring MVC提供的RestTemplate工具类可以简化服务调用过程:
- RestTemplate封装了调用Get请求或Post请求的接口。
- 可以手动指定httpmessageConverter,指定控制器方法接收参数和返回结果数据的转换格式
- 可以设置底层连接方式:将第三方的httpClient作为参数,封装到RestTemplate,第三方的httpclient能够实现连接超时、异常重试次数等功能
- 设置拦截器,实现ClientHttpRequestInterceptor接口:拦截restTemplate发送出去的请求,可以修改请求信息,像给请求添加Http Header。
@Component
public class ActionTrackInterceptor implements ClientHttpRequestInterceptor {
@Autowired
ActionIdGenerator actionIdGenerator;
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
HttpHeaders headers = request.getHeaders();
// 加入自定义字段
headers.add("actionId", actionIdGenerator.generate());
// 保证请求继续被执行
return execution.execute(request, body);
}
}