Reputation: 537
I'm working in a SpringBoot project where I'm developing a rest endpoint which will receive a few parameters and based on these parameters I will create a uri and I'll call another external endpoint to retrieve an image.
Right now I have a rest controller with the following endpoint:
@GetMapping(value = "/{param1}/{param2}/{param3}/{param4}", produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] getImageryBaseMap(@PathVariable("param1") Long param1, @PathVariable("param2") Long param2,
@PathVariable("param3") Long param3, @PathVariable("param4") Long param4)
throws IOException{
//calls my service
return myService.getMyMethod(param1, param2, param3, param4);
}
On myService class I make the call to an external endpoint.
public byte[] retrieveImageryBaseMap(Long param1, Long param2, Long param3, Long param4){
String url = "https://host-name:6443/external/Image/export?bbox="+ param1 +"%" + param2+ "+%"+ param3 + "%" + param4 +"&format=png&f=image";
// here I call the external api endpoint to retrieve an image
byte[] image = getImage(url);
return image;
}
My questions would be:
1) What is the best approach/practices to manage creating the url above? I basically hardcoded almost all the url above just replacing the values by the parameters coming from the method retrieveImageryBaseMap . Would like to know if there's a better approach for that or if it's ok.
2)I also hardcoded the host name and the port in the url String url = "https://host-name:6443/external/Image/export?bbox="+ param1 +"%" + param2+ "+%"+ param3 + "%" + param4 +"&format=png&f=image";
Right now I'm just testing this using the dev host-name, but in production the host name and port will be different. So also would like to ask the best approach/practice to manage the host name in the url? Should I hardcoded like that or use a different approach?
Guys much appreciate any help, I'm working by myself and unfortunately don't have a mentor to ask those sort of questions and got stuck here.
Cheers!
Upvotes: 1
Views: 4130
Reputation: 2211
You can use UriComponentBuilder for such purposes it’s very flexible
Here is an example :
String URI = UriComponentsBuilder.newInstance()
.scheme("https").host("host-name").port(6443).pathSegment("external”,”Image”,”export”)
.queryParam(“paramName1”, value1)
.queryParam(“paramName2”,value2)
.build(). toUriString();
Here is url for documentation https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriComponentsBuilder.html
Upvotes: 2