Java(Android)中的URLEncoder编码/URLDecoder解码

16

我想在一个应用程序中使用URLEncoder/URLDecoder类(java.net.URLEncoder/URLDecoder)以及它的方法:encode(String s, String enc)/decode(String s, String enc),但是我不知道字符串参数enc可以设置成什么值?

我想编码/解码在"x-www-form-urlencoded" MIME内容类型中的内容。

谢谢您的帮助。

5个回答

18

编码参数是您正在使用的字符编码。例如 "UTF-8"


所以我必须这样写:encode("hello", "x-www-form-urlencoded") 还是对于 "x-www-form-urlencoded" 应该写成 encode("hello", "UTF-8")? - Michaël
你需要编写 encode("hello", "UTF-8")。x-www-form-urlencoded 总是结果的类型。编码参数指的是你的输入数据。 - jgre
3
有没有针对可能的字符编码预定义的常量? - Janusz
6
安卓文档太糟糕了!URLEncoder类的文档甚至都没提到“UTF-8”。http://developer.android.com/reference/java/net/URLEncoder.html - Someone Somewhere

4

首先你需要设置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");

我已经完成了以下操作:
  • HttpPost post = new HttpPost("url");
  • post.setHeader("Content-Type", "application/x-www-form-urlencoded");
  • String encodedString = URLEncoder.encode("hello","UTF-8");
  • StringEntity temp;
  • temp.setContentEncoding(encodedString);
  • post.setEntity(temp); 然后使用post作为参数执行DefaultHttpClient。
- Michaël
问题实际上是因为我在encode(String s, String enc)中放了"application/x-www-form-urlencoded"而不是"UTF-8"。再次感谢。 - Michaël

1

JavaDoc没有提到所有可能的编码格式,也没有看到一个可能列出它们的ENUM的链接。 - fIwJlxSzApHEZIl

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/,则返回一个空字符串。如果文件名部分中有反斜杠,则会保留它。
如果需要带扩展名的短名称,则可以去掉最后两行。

0

URLEncoderURLDecoder都是异常Throwable,因此必须至少被try/catch块包围。但是使用android.net.Uri有一个更简单的方法:

Uri.decode(string);
Uri.encode(string);

这些是静态方法,使用 utf-8 编码,自 API-1 起可用,不会抛出任何异常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接