在Java中,我想转换这个:

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

:

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

这是我目前所拥有的:

class StringUTF 
{
    public static void main(String[] args) 
    {
        try{
            String url = 
               "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do" +
               "%3Frequest_type%3D%26type%3Dprivate";

            System.out.println(url+"Hello World!------->" +
                new String(url.getBytes("UTF-8"),"ASCII"));
        }
        catch(Exception E){
        }
    }
}

但这并不正确。这些%3A和%2F格式被称为什么?我如何转换它们?


当前回答

%3A和%2F是URL编码字符。使用下面的java代码将它们转换回:和/

String decoded = java.net.URLDecoder.decode(url, "UTF-8");

其他回答

public String decodeString(String URL)
    {

    String urlString="";
    try {
        urlString = URLDecoder.decode(URL,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block

        }

        return urlString;

    }

你得到的字符串是application/x-www-form-urlencoded编码。

使用URLDecoder将其转换为Java字符串。

URLDecoder.decode( url, "UTF-8" );

我使用apache commons

String decodedUrl = new URLCodec().decode(url);

默认字符集为UTF-8

如果它是整数值,我们也必须捕获NumberFormatException。

try {
        Integer result = Integer.valueOf(URLDecoder.decode(urlNumber, "UTF-8"));
    } catch (NumberFormatException | UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

使用java.net.URI类:

public String getDecodedURL(String encodedUrl) {
    try {
        URI uri = new URI(encodedUrl);
        return uri.getScheme() + ":" + uri.getSchemeSpecificPart();
    } catch (Exception e) {
        return "";
    }
}

请注意,异常处理可以做得更好,但这与本例没有太大关系。