HttpClientErrorException: 404 null

24,125

I struggled a lot with this exception Even URL is absolutely correct and relative URLs works for POST request. 404 means URL specify in RestTemplate or HttpRequest for GET type method is incorrect due to Query Param or Request Params or Path Params. Reason Query/Path param's value contain special character that converted or interpreted differently. Let Say queryParams is [email protected] which converted into email=test20%xyz41%.com

Solution: Decoding while passing query/path params.

Add Following code at server side [controller code]

ServerSide[Controller]:

import java.net.URLDecoder;
 import java.net.URLEncoder;

String encodedEmail = URLDecoder.decode(email, "UTF-8");

It perfectly working and tested code.

Share:
24,125
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    I try to call the address in the controller using RestTemplate and as a result I want to get OK or NOT FOUND status I do so in this controller

    @GetMapping(value = "/thanks")
    public ModelAndView confirmAccount(
            @RequestParam String token,
            UriComponentsBuilder uriComponentsBuilder
    ) {
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<Object> entity = new HttpEntity<>(new HttpHeaders());
    
        UriComponents uriComponents
                = uriComponentsBuilder.path("/register/token/{token}").buildAndExpand(token);
    
        ResponseEntity<Boolean> response = restTemplate
                .exchange(uriComponents.toUri(),
                          HttpMethod.PUT,
                          entity,
                          Boolean.class);
    
        return response.getStatusCode().toString().equals("200")
                ?  new ModelAndView("redirect:/signIn") : new ModelAndView("tokenNotFound");
    }
    

    I call this address of the controller.

    @RequestMapping(value = "/register/token/{token}", method = RequestMethod.PUT)
    public
    HttpEntity<Boolean> confirmAccount(
            @PathVariable String token
    ) {
        Optional<User> userOptional = userService.findByActivationToken(token);
    
        if(userOptional.isPresent()) {
            User user = userOptional.get();
    
            user.setActivationToken(null);
            user.setEnabled(true);
    
            userService.saveUser(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    
        return ResponseEntity.ok(true);
    }
    

    As a result, she throws me out in the console

    org.springframework.web.client.HttpClientErrorException: 404 null
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:628) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:549) ~[spring-web-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at com.service.app.controller.RegisterController.confirmAccount(RegisterController.java:40) ~[classes/:na]
    

    Why does RestTemplate not want to return the status 404 as a result? enter code here

    • Amit K Bist
      Amit K Bist over 6 years
      What url are you calling to test the flow?
    • Admin
      Admin over 6 years
      Sorry. I map the entire controller to' /register'. Here I corrected the address.
    • Saurabh
      Saurabh over 6 years
      When is HttpClientErrorException exception occurring, while calling "/thanks" or "/register/token"? More stacktrace can be useful
    • Amit K Bist
      Amit K Bist over 6 years
      First you need to check if you are calling /register/token/{token} it correctly? If it is actually going inside confirmAccount Method, that you can check by putting a breakpoint of a log statement. If it is not hitting this method then problem is in calling the method which will also throw 404 but it will be thrown by Spring.
  • vanillaSugar
    vanillaSugar over 4 years
    Exactly. RestTemplate throws exceptions and you have to catch them baeldung.com/spring-rest-template-error-handling
  • Arun
    Arun over 2 years
    This one woked for me