Android中的URL编码

您如何在Android中编码URLjava

我觉得是这样的: android

final String encodedURL = URLEncoder.encode(urlAsString, "UTF-8");
URL url = new URL(encodedURL);

若是我作了上述状况, http://urlAsString被替换http%3A%2F%2FencodedURL ,而后我获得一个java.net.MalformedURLException当我使用的URL。 app


#1楼

对于android,我将使用String android.net.Uri.encode(String s) ui

使用UTF-8方案将给定字符串中的字符编码为'%'转义的八位字节。 保留字母(“ AZ”,“ az”),数字(“ 0-9”)和未保留的字符(“ _- !.〜'()*”)完好无损。 编码全部其余字符。 编码

例/ url

String urlEncoded = "http://stackoverflow.com/search?q=" + Uri.encode(query);

#2楼

你也能够用这个 spa

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

这是最简单的方法 .net


#3楼

try {
                    query = URLEncoder.encode(query, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

#4楼

您无需对整个URL进行编码,而仅对其中一部分来自“不可靠的来源”进行编码。 code

String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;

另外,您能够使用不引起检查异常的DroidParts的 Strings.urlEncode(String str)orm

或使用相似

String uri = Uri.parse("http://...")
                .buildUpon()
                .appendQueryParameter("key", "val")
                .build().toString();

#5楼

您能够使用如下方法

public static String parseUrl(String surl) throws Exception
{
    URL u = new URL(surl);
    return new URI(u.getProtocol(), u.getAuthority(), u.getPath(), u.getQuery(), u.getRef()).toString();
}

要么

public String parseURL(String url, Map<String, String> params)
{
    Builder builder = Uri.parse(url).buildUpon();
    for (String key : params.keySet())
    {
        builder.appendQueryParameter(key, params.get(key));
    }
    return builder.build().toString();
}

第二个比第一个好。

相关文章
相关标签/搜索