我正在开发一个 Spring Boot 应用程序,我目前在尝试向外部 Web 服务发送 http 请求时遇到问题(具体来说,URL 是这些:https ://dgidb.org/api/v2/interactions.json ?genes=和https://api.pharmgkb.org/v1/data/clinicalAnnotation?location.genes.symbol=,显然带有正确的参数,例如“FLT4”)。
我有一个休息控制器,其中一些方法映射到获取请求,每个请求都向 Web 服务发出另一个请求。当我们的前端调用其中一个 API 时,后端调用上述 Web 服务之一,然后通过 Jackson ObjectMapper 将生成的 json 序列化并像往常一样发送到我们的前端。
它在我的机器上完美运行,但它根本没有部署在运行 Ubuntu 的服务器上。事实上,当被前端调用时,它会给出错误 500 和 CORS Missing Allow Origin 错误。为了确保这不是与实现相关的问题,我和我的同事尝试了上述方法的不同实现,使用 WebClient (WebFlux) 以及 RestTemplate 甚至 curl;我们还尝试使用注释@CorsOrigin(origins = "*")
,甚至手动将注释“Access-Control-Allow-Origin”添加到生成的 ResponseEntity,但结果是一样的:它在部署的应用程序上不起作用。
服务器上产生的日志如下:
卷曲实现:
Forwarding to error page from request [/endpoint_name] due to exception [No content to map due to end-of-input at [Source: (String)""; line: 1, column: 0]] com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input at [Source: (String)""; line: 1, column: 0]
休息模板:
.ResourceAccessException: I/O error on GET request for "https://api.pharmgkb.org/v1/data/clinicalAnnotation": Connection timed out (Connection timed out); nested exception is java.net.ConnectException: Connection timed out (Connection timed out)
网络客户端:
.ErrorPageFilter [https-openssl-nio-8443-exec-57] Forwarding to error page from request [/endpoint_name] due to exception [Timeout on blocking read for 30000000000 NANOSECONDS] java.lang.IllegalStateException: Timeout on blocking read for 30000000000 NANOSECONDS
我们应用程序中的所有其他 API 都按预期工作,只有调用上述外部 Web 服务的 API 才会出现问题。
这是一个代码示例:
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/controller_path")
public class MyController {
private ObjectMapper objectMapper;
@Autowired
public MyController(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@GetMapping("/api_endpoint")
public ResponseEntity<PharmGKB> getPharmGKBDrugs(@RequestParam(name = "gene") String gene) throws Exception {
final String uri =
"https://api.pharmgkb.org/v1/data/clinicalAnnotation?location.genes.symbol=" + gene.toUpperCase();
final RestTemplate restTemplate = new RestTemplate();
String responseBody;
try {
final ResponseEntity<String> response = restTemplate
.exchange(uri, HttpMethod.GET, null, String.class);
responseBody = response.getBody();
} catch (HttpClientErrorException | HttpServerErrorException e) {
responseBody = e.getResponseBodyAsString();
}
final PharmGKB pharmGKB = objectMapper.readValue(responseBody, PharmGKB.class);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Access-Control-Allow-Origin", "*");
ResponseEntity<PharmGKB> response = new ResponseEntity<>(pharmGKB, responseHeaders, HttpStatus.OK);
return response;
}
}
拜托,你能帮我解决这个问题吗?先感谢您。