后端透传代理实现
参数设计
- 增加的一个target参数,用于表明需要代理的目标地址
- 其他query参数透传
- header参数透传
代码实现
@RestController
public class HomeController {
@GetMapping("/backend/proxy")
public ResponseEntity<?> proxy(@RequestParam MultiValueMap<String, String> params, @RequestHeader MultiValueMap<String, String> heads) {
if (!params.containsKey("target")) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("{\"message\": \"target param is required\"}");
}
String url = params.remove("target").get(0);
System.out.println("url: " + url);
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("{\"message\": \"target value invalid\"}");
}
String result = WebClient.create().get().uri(uriBuilder -> uriBuilder.scheme(uri.getScheme())
.host(uri.getHost()).path(uri.getPath()).queryParams(params).build())
.headers(headers -> headers.addAll(heads)).retrieve()
.bodyToMono(String.class).block();
return ResponseEntity.ok(result);
}
}