how do I encode a complete http url String correctly?

后端 未结 2 1034
清酒与你
清酒与你 2021-01-19 17:18

I get a url string from a user and would like to transform it to a legal http url:

\"http://one.two/three?four five\" should turn into \"htt

2条回答
  •  灰色年华
    2021-01-19 17:42

    With external library:

    import org.apache.commons.httpclient.util.URIUtil;
    String myUrl_1= "http://one.two/three?four five";
    System.out.println(URIUtil.encodeQuery(myUrl_1));
    

    And the output:

    http://one.two/three?four%20five
    

    Or

    String webResourceURL = "http://stackoverflow.com/search?q= s";
    System.out.println(URIUtil.encodeQuery(webResourceURL));
    

    And the output:

    http://stackoverflow.com/search?q=%3Cscript%3Ealert(1)%3C/script%3E%20s
    

    And the Maven dependency

    
        commons-httpclient
        commons-httpclient
        3.1
    
    

提交回复
热议问题