How to do URL decoding in Java?

前端 未结 9 1680
轮回少年
轮回少年 2020-11-22 05:01

In Java, I want to convert this:

https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type

To thi

9条回答
  •  面向向阳花
    2020-11-22 05:17

    This has been answered before (although this question was first!):

    "You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."

    As URL class documentation states:

    The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL().

    The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396.

    Basically:

    String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
    System.out.println(new java.net.URI(url).getPath());
    

    will give you:

    https://mywebsite/docs/english/site/mybook.do?request_type
    

提交回复
热议问题