To get the request URL, found below approaches in stack overflow.
1st approach:
@Autowired
private HttpServletRequest request;
public void getURL(){
String url=request.getRequestURL().toString();
}
2nd approach:
public void getURL(){
String url=ServletUriComponentsBuilder.fromCurrentRequestUri().toUriString();
}
3rd approach:
public void getURL(){
HttpServletRequest request=
((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
String url=request.getRequestURL().toString();
}
I am confused which one to use to get the request URL in the spring boot application.
if i go with 3rd approach, then should i need to create bean of RequestContextListener in Configuration class as shown below?
@Bean
public RequestContextListener requestContextListener(){
return new RequestContextListener();
}
CodePudding user response:
Actually it is very simple. Create a class that is annotated as @RestController
and in it create a method that is handling your mapping. In that method list HttpServletRequest request
as your parameter. That's it, in this method you will get it as parameter and can use it. Below is one of my working examples that does just that.
@RestController
@RequestMapping("/upload")
public class UploadTestController {
@PostMapping
public ResponseEntity<String> uploadTest(HttpServletRequest request) {
try {
String lengthStr = request.getHeader("content-length");
int length = TextUtils.parseStringToInt(lengthStr, -1);
if(length > 0) {
byte[] buff = new byte[length];
ServletInputStream sis =request.getInputStream();
int counter = 0;
while(counter < length) {
int chunkLength = sis.available();
byte[] chunk = new byte[chunkLength];
sis.read(chunk);
for(int i = counter, j= 0; i < counter chunkLength; i , j ) {
buff[i] = chunk[j];
}
counter = chunkLength;
if(counter < length) {
TimeUtils.sleepFor(5, TimeUnit.MILLISECONDS);
}
}
Files.write(Paths.get("C:\\Michael\\tmp\\testPic.jpg"), buff);
}
} catch (Exception e) {
System.out.println(TextUtils.getStacktrace(e));
}
return ResponseEntity.ok("Success");
}
}
CodePudding user response:
try this:
@RestController
@RequestMapping("/url")
public class YourController {
@PostMapping
public ResponseEntity<String> postSomething(HttpServletRequest request) {
String url = request.getRequestURL();
// your business logic...
}