我想在一个应用程序中使用URLEncoder/URLDecoder类(java.net.URLEncoder/URLDecoder)以及它的方法:encode(String s, String enc)/decode(String s, String enc),但是我不知道字符串参数enc可以设置成什么值?
我想编码/解码在"x-www-form-urlencoded" MIME内容类型中的内容。
谢谢您的帮助。
编码参数是您正在使用的字符编码。例如 "UTF-8"
。
首先你需要设置content-type为“x-www-form-urlencoded”。然后,无论你想要编码的内容是什么,都使用“UTF-8”进行编码。
例如:
设置content为“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");
JavaDoc 包含了所有的细节
我个人最喜欢的:
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;
}
https://stackoverflow.com/
或https://stackoverflow.com/questions/
,则返回一个空字符串。如果文件名部分中有反斜杠,则会保留它。URLEncoder
和URLDecoder
都是异常Throwable
,因此必须至少被try/catch块包围。但是使用android.net.Uri
有一个更简单的方法:
Uri.decode(string);
Uri.encode(string);
这些是静态方法,使用 utf-8 编码,自 API-1 起可用,不会抛出任何异常。