public static String encode(final CharSequence url)
      throws HttpRequestException {
    URL parsed;
    try {
      parsed = new URL(url.toString());
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }

    String host = parsed.getHost();
    int port = parsed.getPort();
    if (port != -1)
      host = host + ':' + Integer.toString(port);

    try {
      String encoded = new URI(parsed.getProtocol(), host, parsed.getPath(),
          parsed.getQuery(), null).toASCIIString();
      int paramsStart = encoded.indexOf('?');
      if (paramsStart > 0 && paramsStart + 1 < encoded.length())
        encoded = encoded.substring(0, paramsStart + 1)
                  + encoded.substring(paramsStart + 1).replace("+", "%2B");
      return encoded;
    } catch (URISyntaxException e) {
      IOException io = new IOException("Parsing URI failed");
      io.initCause(e);
      throw new HttpRequestException(io);
    }
  }
public static String encode ( final CharSequence url ) throws HttpRequestException { URL parsed ; try { parsed = new URL ( url . toString ( ) ) ; } catch ( IOException e ) { throw new HttpRequestException ( e ) ; } String host = parsed . getHost ( ) ; int port = parsed . getPort ( ) ; if ( port != - 1 ) host = host + ':' + Integer . toString ( port ) ; try { String encoded = new URI ( parsed . getProtocol ( ) , host , parsed . getPath ( ) , parsed . getQuery ( ) , null ) . toASCIIString ( ) ; int paramsStart = encoded . indexOf ( '?' ) ; if ( paramsStart > 0 && paramsStart + 1 < encoded . length ( ) ) encoded = encoded . substring ( 0 , paramsStart + 1 ) + encoded . substring ( paramsStart + 1 ) . replace ( "+" , "%2B" ) ; return encoded ; } catch ( URISyntaxException e ) { IOException io = new IOException ( "Parsing URI failed" ) ; io . initCause ( e ) ; throw new HttpRequestException ( io ) ; } }
Encode the given URL as an ASCII {@link String}
<p>
This method ensures the path and query segments of the URL are properly
encoded such as ' ' characters being encoded to '%20' or any UTF-8
characters that are non-ASCII. No encoding of URLs is done by default by
the {@link HttpRequest} constructors and so if URL encoding is needed this
method should be called before calling the {@link HttpRequest} constructor.

@param url
@return encoded URL
@throws HttpRequestException