我想在应用程序中使用URLEncoder / URLDecoder类(java.net.URLEncoder / URLDecoder)和方法:encode(String s,String enc)/ decode(String s,String enc),但我不知道知道String参数enc的值是什么? 我想在“x-www-form-urlencoded”MIME内容类型中编码/解码。 谢谢你的帮助。
答案 0 :(得分:18)
编码参数是您正在使用的字符编码。 For example "UTF-8"
。
答案 1 :(得分:4)
首先,您需要将内容类型设置为“x-www-form-urlencoded”。然后,无论您想要编码什么内容,请使用“UTF-8”对其进行编码。
例如:
将内容设置为“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");
或者如果您使用的是JSP,那么您可以在其上面写下以下内容。
<%@ 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">
并使用URLEncoder:
String encodedString = URLEncoder.encode("hello","UTF-8");
答案 2 :(得分:1)
JavaDoc包含所有细节
答案 3 :(得分:0)
URLEncoder
和URLDecoder
都是异常Throwable
,因此必须至少被try / catch块包围。但是,使用android.net.Uri
:
Uri.decode(string);
Uri.encode(string);
这些是静态方法,使用utf-8,自API-1起可用,并且不会抛出任何异常。
答案 4 :(得分:0)
我个人的最爱:
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;
}
如果URL没有文件名部分,则返回空字符串,如https://stackoverflow.com/
或https://stackoverflow.com/questions/
。如果文件名部分有反斜杠,则保留。
如果你需要带有扩展名的短名称,你可以去除最后两行。