SpringBoot报文转发
SpringBoot
仿Zuul
报文转发
基于RestTemplate
从request
中提取出header
、body
等内容,构造一个RequestEntity
,后续可以用RestTemplate
来发送请求
请求入口RestController
public final static String DELEGATE_PREFIX = "/api";
public final static String TARGET_URL = "http://hlooc.cn";
@Autowired
private RoutingDelegate routingDelegate;
@RequestMapping(value = "/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity catchAll(HttpServletRequest request, HttpServletResponse response) {
return routingDelegate.redirect(request, response, TARGET_URL, DELEGATE_PREFIX);
报文处理RoutingDelegate
private static final Logger logger = LoggerFactory.getLogger(RoutingDelegate.class);
public ResponseEntity<String> redirect(HttpServletRequest request, HttpServletResponse response,String routeUrl, String prefix) {
try {
// build up the redirect URL
String redirectUrl = createRedictUrl(request,routeUrl, prefix);
RequestEntity requestEntity = createRequestEntity(request, redirectUrl);
return route(requestEntity);
} catch (Exception e) {
logger.error("处理异常:{}",e.getLocalizedMessage(),e);
return new ResponseEntity("REDIRECT ERROR", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
private String createRedictUrl(HttpServletRequest request, String routeUrl, String prefix) {
String queryString = request.getQueryString();
return routeUrl + request.getRequestURI().replace(prefix, "") +
(queryString != null ? "?" + queryString : "");
}
private RequestEntity createRequestEntity(HttpServletRequest request, String url) throws URISyntaxException, IOException {
String method = request.getMethod();
HttpMethod httpMethod = HttpMethod.resolve(method);
MultiValueMap<String, String> headers = parseRequestHeader(request);
byte[] body = parseRequestBody(request);
return new RequestEntity<>(body, headers, httpMethod, new URI(url));
}
private ResponseEntity route(RequestEntity requestEntity) {
RestTemplate restTemplate = new RestTemplate();
// 乱码处理
// List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
// for (HttpMessageConverter<?> messageConverter : messageConverters) {
// if (messageConverter instanceof StringHttpMessageConverter) {
// ((StringHttpMessageConverter) messageConverter).setDefaultCharset(StandardCharsets.UTF_8);
// }
// }
return restTemplate.exchange(requestEntity, Resource.class);
}
private byte[] parseRequestBody(HttpServletRequest request) throws IOException {
InputStream inputStream = request.getInputStream();
return StreamUtils.copyToByteArray(inputStream);
}
private MultiValueMap<String, String> parseRequestHeader(HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
List<String> headerNames = Collections.list(request.getHeaderNames());
for (String headerName : headerNames) {
List<String> headerValues = Collections.list(request.getHeaders(headerName));
for (String headerValue : headerValues) {
headers.add(headerName, headerValue);
}
}
return headers;
}
restTemplate.exchange(requestEntity, Resource.class);
使用Resource
可以解决以下异常:
Could not extract response: no suitable HttpMessageConverter found for response type [class java.lang.Object] and content type [application/octet-stream;charset=GBK]