public static String encodeUrl ( String url ) { Uri uri = Uri . parse ( url ) ; try { Map < String , List < String > > splitQuery = splitQuery ( uri ) ; StringBuilder encodedQuery = new StringBuilder ( ) ; for ( String key : splitQuery . keySet ( ) ) { for ( String value : splitQuery . get ( key ) ) { if ( encodedQuery . length ( ) > 0 ) { encodedQuery . append ( "&" ) ; } encodedQuery . append ( key + "=" + URLEncoder . encode ( value , "UTF-8" ) ) ; } } String queryString = encodedQuery != null && encodedQuery . length ( ) > 0 ? "?" + encodedQuery : "" ; URI baseUri = new URI ( uri . getScheme ( ) , uri . getAuthority ( ) , uri . getPath ( ) , null , uri . getFragment ( ) ) ; return baseUri + queryString ; } catch ( UnsupportedEncodingException ignore ) { } catch ( URISyntaxException ignore ) { } return uri . toString ( ) ; }
This method encodes the query part of an url