how do I encode a complete http url String correctly?

后端 未结 2 1012
清酒与你
清酒与你 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:58

    Use the URL class. For example:

    URL url = new URL(urlString);
    String encodedQueryString = URLEncoder.encode(url.getQuery());
    String encodedUrl = urlString.replace(url.getQuery(), encodedQueryString);
    

    The third line might be different - for example constructing a new URL from all its parts.

提交回复
热议问题