Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot: Prevent decoding for @RequestParam

I have a Spring-Boot (1.5.3) application running on a Tomcat 8.5. Within it, i have a RestController with a single parameter.

This parameter is decoded automatically - which is fine for all other controllers within my application, but for this one, i need the raw request data, since they will be used within another request. Please note that i wold like to only disable the auto-decoding for this Controller/request and keep the normal behaviour everywhere else.

@RestController
@RequestMapping("/rest/test")
public class TestController {

  @RequestMapping("/test")
  public ResponseEntity<String> test(@RequestParam final String test){
    return ResponseEntity.ok("Requested: " + test);
  }
}

Now, if i send access it with

curl localhost/rest/test/test?test=%C3%B6%20%C3%A4

I receive the output:

Requested: ö ä

I would like to have

Requested: %C3%B6%20%C3%A4

Any Ideas?

like image 835
Aracos Avatar asked Jun 09 '17 10:06

Aracos


3 Answers

I had the similar issue with a parameter which had the base64Encoded value, but for me only the + sign was getting converted into space. If I would have used URLEncoder.encode() method, other special characters were also getting converted. So, I solved this by passing the param in RequestBody instead of RequestParam.

PS : This is not a perfect answer for this question. I am just writing this answer for anyone who get the similar problem like this and land to this thread.

like image 84
Sahil Chhabra Avatar answered Nov 08 '22 15:11

Sahil Chhabra


If you need this behavior only in a single place, you can encode the parameter back to the original form using the standard Java URLEncoder inside of the controller body:

@RequestMapping("/test")
public ResponseEntity<String> test(@RequestParam final String test) {
  String encodedParam = URLEncoder.encode(test, "UTF-8");
  return ResponseEntity.ok("Requested: " + encodedParam);
}
like image 37
Daniel Olszewski Avatar answered Nov 08 '22 13:11

Daniel Olszewski


I ended up ensuring, that the received data was did not contain invalid characters.

private static final String VALID_URL_CHARACTER_PATTERN = "^[A-Za-z0-9-._~:/?#\\[\\]@!$&'()*+,;=`.]+$";

private static final String ensureEncoding(final Object obj) {
    if (obj == null) {
        return null;
    }
    String val = obj.toString();
    if (!val.matches(VALID_URL_CHARACTER_PATTERN)) {
        try {
            val = URLEncoder.encode(val, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("Unexpected encoding Problem on value: " + val, e);

        }
    }
    return val;
}
like image 1
Aracos Avatar answered Nov 08 '22 14:11

Aracos