Reputation: 3671
I want to use the URLEncoder/URLDecoder class (java.net.URLEncoder/URLDecoder) in an application and the methods : encode(String s, String enc)/decode(String s, String enc), but I don't know what can be the value of the String argument enc? I want to encode/decode in the "x-www-form-urlencoded" MIME content type. Thank you for your help.
Upvotes: 16
Views: 57127
Reputation: 10112
My personal favourite:
static String baseNameFromURL(URL url) {
String shortName;
String path = url.getPath();
String escaped = path.substring(path.lastIndexOf('/') + 1);
try {
shortName = URLDecoder.decode(escaped, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Error(e.getMessage(), e);
}
int period = shortName.lastIndexOf('.');
return period > -1 ? shortName.substring(0, period) : shortName;
}
Returns an empty String if the URL doesn’t have a file name part, like https://stackoverflow.com/
or https://stackoverflow.com/questions/
. If there is a backslash in the file name part, it is conserved.
You may strip off the last two lines if you need the short name with extension instead.
Upvotes: 0
Reputation: 6561
URLEncoder
and URLDecoder
both are exception Throwable
and thus must be at least enclosed by try/catch block. However there is a litle bit simplier way using android.net.Uri
:
Uri.decode(string);
Uri.encode(string);
Those are static methods, uses utf-8, available since API-1 and throws no exception.
Upvotes: 0
Reputation: 787
The encoding parameter is the character encoding you're using. For example "UTF-8"
.
Upvotes: 18
Reputation: 1615
First you need to set the content-type as a 'x-www-form-urlencoded'. Then whatever content you would like to encode, encode it using "UTF-8".
For example:
For setting content to 'x-www-form-urlencoded':
URL url = new URL("http://www.xyz.com/SomeContext/SomeAction"); <br>
URLConnection urlConnection = url.openConnection();<br>
....<br>
....<br>
urlConnection.setRequestProperty("Content-type","application/x-www-form-urlencoded");
Or if you are using some JSP then you can write the following on top of it.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %><br>
< META http-equiv="Content-Type" content="text/html; charset=UTF-8">
< FORM action="someaction.jsp" enctype="application/x-www-form-urlencoded" name="InputForm" method="POST">
And to use URLEncoder:
String encodedString = URLEncoder.encode("hello","UTF-8");
Upvotes: 4