Java Spring RestTemplate:URI 不是绝对的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45328058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring RestTemplate: URI is not absolute
提问by Alessandro
I'm trying to connect to a Spring RESTful serviceon the same server where my webapp is running.
我正在尝试连接到运行我的 web 应用程序的同一台服务器上的Spring RESTful 服务。
I'd like to use a "relative" path because it could be installed on several environments (localhost, test, production) but I get the error message: URI is not absolute
.
我想使用“相对”路径,因为它可以安装在多个环境(本地主机、测试、生产)上,但我收到错误消息:URI is not absolute
.
How can I call a service running on another webapp on the same server?
如何调用在同一台服务器上的另一个 web 应用程序上运行的服务?
My code is like following:
我的代码如下:
final RestTemplate restTemplate = new RestTemplate();
URI uri;
try {
String url = "app2/myservice?par=1";
uri = new URI(url);
String result = restTemplate.getForObject(uri, String.class);
System.out.println(result);
} catch (URISyntaxException e) {
logger.error(e.getMessage());
}
Thanks.
谢谢。
Update:
更新:
I solved it by getting the host, port, etc... from the request
, could it be a right and elegant solution? This's my actual simplified code:
我通过从 中获取主机、端口等来解决它request
,这可能是一个正确而优雅的解决方案吗?这是我实际的简化代码:
String scheme = request.getScheme();
String userInfo = request.getRemoteUser();
String host = request.getLocalAddr();
int port = request.getLocalPort();
String path = "/app2/myservice";
String query = "par=1";
URI uri = new URI(scheme, userInfo, host, port, path, query, null);
boolean isOK = restTemplate.getForObject(uri, Boolean.class);
if (isOK) {
System.out.println("Is OK");
}
采纳答案by banncee
You cannot do it as your code in the first snippet; the URI must FULLY identify the resource you are trying to get to. Your second snippet is the pretty much the only way you can do what you're trying to do. There may be other ways, but I can't think of any off the top of my head.
您不能将其作为第一个代码段中的代码;URI 必须完全标识您尝试访问的资源。你的第二个片段几乎是你可以做你想做的事情的唯一方法。可能还有其他方法,但我想不出任何办法。
Of course, with your approach, you are dictating your system architecture and deployment model in code, which is almost never a good idea.
当然,使用您的方法,您是在代码中规定您的系统架构和部署模型,这几乎从来都不是一个好主意。
回答by kushal Baldev
Your URL app2/myservice?par=1
is not complete if your service running on another web app or the same server.
app2/myservice?par=1
如果您的服务在另一个 Web 应用程序或同一服务器上运行,则您的URL不完整。
You have to complete the path by giving base URL means localhost:8080/yourApp/app2/myservice?par=1
then the things might work for you.
您必须通过提供基本 URL 来完成路径,localhost:8080/yourApp/app2/myservice?par=1
然后这些东西可能对您有用。
Also, check the Package access.
此外,检查包访问。
回答by user1527893
Provide a full path like http://localhost:8080/app2/myservice?par=1. Hope this helps.
提供完整路径,如http://localhost:8080/app2/myservice?par=1。希望这可以帮助。