我有一个 RestTemplate
,我用 RestTemplateBuilder
构建它。我为构建器设置了 rootUri。在下面的方法 (updateState1) 中,有时我会收到“URI 不是绝对的”错误。例如,当我同时调用此方法 2 次时,我经常遇到 1 个错误。
编辑和解决方案 :
我在camunda进程的服务任务中使用这个RestTemplate
。我在与 oracle 数据库具有不同时区的 kubernetes 容器中启动了这个项目。当我添加时区变量时,一切正常。
Spring启动版本:2.1.1.RELEASE
这是我的代码:
@Component
@Slf4j
public class CoreServiceClient {
private RestTemplate restTemplate;
private static final String root = "http://localhost:8080/test/api/";
public CoreServiceClient(RestTemplateBuilder restTemplateBuilder) {
restTemplate = restTemplateBuilder.rootUri(root).build();
}
public void updateState1(UpdateParam updateParam) {
HttpHeaders headers = generateHeader();
UpdateRequest updateRequest = new UpdateRequest(updateParam.getState());
HttpEntity<UpdateRequest> httpEntity = new HttpEntity<>(updateRequest, headers);
ResponseEntity<String> response = restTemplate.exchange(
"/food/{id}/state",
HttpMethod.PUT, httpEntity, String.class, updateParam.getId());
}
public void updateState2(String id) {
HttpHeaders headers = generateHeader();
UpdateRequest updateRequest = new UpdateRequest("done");
HttpEntity<UpdateRequest> httpEntity = new HttpEntity<>(updateRequest, headers);
ResponseEntity<String> response = restTemplate.exchange(
"/food/{id}/state",
HttpMethod.PUT, httpEntity, String.class, id);
}
}
原因(堆栈跟踪):
Caused by: java.lang.IllegalArgumentException: URI is not absolute
at java.net.URI.toURL(URI.java:1088)
at org.springframework.http.client.SimpleClientHttpRequestFactory.createRequest(SimpleClientHttpRequestFactory.java:145)
at org.springframework.http.client.support.HttpAccessor.createRequest(HttpAccessor.java:87)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:730)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:669)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:578)
at com.test.client.CoreServiceClient.updateState(CoreServiceClient.java:39)
at sun.reflect.GeneratedMethodAccessor263.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.camunda.bpm.engine.impl.javax.el.BeanELResolver.invoke(BeanELResolver.java:479)
... 85 more
最佳答案
删除 root 中的 /
:
private static final String root = "http://localhost:8080/test/api";
RestTemplate 接受 uriTemplate 只要它们以
/
开头,所以你的根应该没有它。如果它不是以 /
开头,它会将其视为完整的 URL
关于java - 带有 rootUri 返回 URI 的 Spring RestTemplate 不是绝对错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54206409/