用java代码实现在gateway响应头中添加Content-Type等于application/json
时间: 2024-02-18 13:59:27 浏览: 52
$.ajax中contentType: “application/json” 的用法详解
可以使用以下代码实现:
```java
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class ContentTypeFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
return chain.filter(exchange);
}
@Override
public int getOrder() {
return -1;
}
}
```
这个过滤器会在所有请求前面添加 Content-Type 响应头,并设置为 application/json 。
阅读全文