how to url encode in android? how to url encode in android? android android

how to url encode in android?


URL encoding is done in the same way on android as in Java SE;

try {    String url = "http://www.example.com/?id=123&art=abc";    String encodedurl = URLEncoder.encode(url,"UTF-8");    Log.d("TEST", encodedurl);} catch (UnsupportedEncodingException e) {    e.printStackTrace();} 


Also you can use this

private static final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);

it's the most simple method


As Ben says in his comment, you should not use URLEncoder.encode to full URLs because you will change the semantics of the URL per the following example from the W3C:

The URIs http://www.w3.org/albert/bertram/marie-claude and http://www.w3.org/albert/bertram%2Fmarie-claude are NOT identical, as in the second case the encoded slash does not have hierarchical significance.

Instead, you should encode component parts of a URL independently per the following from RFC 3986 Section 2.4

Under normal circumstances, the only time when octets within a URI are percent-encoded is during the process of producing the URI from its component parts. This is when an implementation determines which of the reserved characters are to be used as subcomponent delimiters and which can be safely used as data. Once produced, a URI is always in its percent-encoded form.

So, in short, for your case you should encode/escape your filename and then assemble the URL.