Alessandro
Alessandro

Reputation: 4472

Spring RestTemplate: URI is not absolute

I'm trying to connect to a Spring RESTful service on the same server where my webapp is running.

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.

How can I call a service running on another webapp on the same server?

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:

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");
}

Upvotes: 19

Views: 96650

Answers (4)

pranav patil
pranav patil

Reputation: 21

If you are using service discovery by using the Netflix Eureka discovery server. You need to provide a full path like http://app2/myservice?par=1.

Upvotes: 1

user1527893
user1527893

Reputation: 29

Provide a full path like http://localhost:8080/app2/myservice?par=1. Hope this helps.

Upvotes: 3

kushal Baldev
kushal Baldev

Reputation: 769

Your URL app2/myservice?par=1 is not complete if your service running on another web app or the same server.

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.

Also, check the Package access.

Upvotes: 10

banncee
banncee

Reputation: 969

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.

Of course, with your approach, you are dictating your system architecture and deployment model in code, which is almost never a good idea.

Upvotes: 4

Related Questions