简体   繁体   中英

Handling special characters in REST API

I am having following URL

http://context_path/info/abc/def

which gets converted like

http://context_path/info/abc%2Fdef

Where as my controller mapping is:

@RequestMapping(value = "/info/{id}", method = RequestMethod.GET)

here 'id' contains forward slash (/). So when I hit the URL I get 400 Bad Request .

I know the possible solutions

  • Setting tomcat to allow forward slash.
  • Use URL encoding.
  • Use of @RequestParam instead of @PathVariable .

But above solution are not possible for me.

Q. Is there any other solution like (using regular expression or changing the mapping or anything else) to the problem ? Also how the tomcat treats other special characters ('.' , ''' , ':' , ',') correctly and controller gets hit but not for '/' .

Tried but not working :

1) @RequestMapping(value = "/info/{id:.*}", method = RequestMethod.GET)
2) @RequestMapping(value = "/info/{id}/**", method = RequestMethod.GET)
3) @RequestMapping(value = "/info/**", method = RequestMethod.GET)

It is not nice, but you can use Base64 transformation .

So you client will send an encoded id and you decode it back in your controller.

import org.apache.commons.codec.binary.Base64;

@RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
public String get(@PathVariable String id) {
    final String realId = new String(new Base64(true).encodeBase64URLSafe(id));
    [...]
}

EDIT: You should use url save implementation of Base64:

You can use something like this How to handle requests that includes forward slashes (/)?

But it has it's limitations, I would suggest you to replace the forward slash with something else like '#' while calling the api and then again replace it back to forward slash before processing it in rest controller.

If replacing while calling the api is not possible then you can use filter and replace the data there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM