Triet Doan
Triet Doan

Reputation: 12083

How to create a URL pointing to a REST endpoint in your system at runtime with Spring Boot?

I'm using Spring Boot to build a REST API. In my situation, there are 2 controllers: ExportController and ImportController. Please check the example code here:

Export Controller:

@RestController
public class ExportController {

    @GetMapping(value = "/export", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<Resource> export(@RequestParam("id") String id) {
        // Processing...
    }

}

Import Controller:

@RestController
public class ImportController {

    @PostMapping(value = "/import", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> importData(HttpServletRequest request) {
        // Processing...

       // What should I do here?
       String url = ...
    }

}

Inside my ImportController, I want to generate a URL pointing to the /export endpoint, e.g. http://www.example.com/export?id=1234.

I don't configure anything about the host or port in the application.properties. I want to get them at runtime.

Could you please show me how to achieve it? I searched a lot on the Internet but couldn't find the answer. Thank you for your help.

Upvotes: 0

Views: 2125

Answers (3)

Raja Anbazhagan
Raja Anbazhagan

Reputation: 4564

You can make use of ServletUriComponentsBuilder that comes with Spring framework since 3.1.RELEASE.

Given that you have access to current request, You can do something like below.

 UriComponents uriComponents = ServletUriComponentsBuilder
        .fromRequest(httpServletRequest)
        .replacePath("/export")
        .queryParam("id",1234)
        .build();
 String url = uriComponents.toUri();

Upvotes: 0

Vinicius P
Vinicius P

Reputation: 1

@RestController
public class ImportController {
    @PostMapping(value = "/import", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> importData(HttpServletRequest request) {
        // Processing...

       String url = request.getScheme() + "://" + 
            request.getServerName() + ":" +                           
            request.getServerPort() + "/export";
    }
}

Upvotes: 0

Not a JD
Not a JD

Reputation: 1902

If you can live with bringing spring-hateoas into your project then this will work:

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

@RestController
public class ImportController {

    @PostMapping(value = "/import", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> importData(HttpServletRequest request) {
        String someId = "1234";

        ControllerLinkBuilder linkBuilder = ControllerLinkBuilder.linkTo(methodOn(ExportController.class).export(someId));

        URI uri = linkBuilder.toUri();

        return ResponseEntity.ok(uri);
    }

}

This yields http://localhost:8080/export?id=1234

Upvotes: 1

Related Questions