如何在android中编码url,如下所示?

时间:2015-01-29 11:07:38

标签: android url encoding

我想转换下面的网址

https://sdcude.pdakmddda.at/sdtddio/img/thumbnails/original/ÖffnungszeitenTest-638.jpg

https://sdcude.pdakmdda.at/sdtddio/img/thumbnails/original/%C3%96ffnungszeiten%20Test-638.jpg

Logcat01-29 16:40:36.195: W/System.err(15131): java.net.MalformedURLException: Protocol not found: https%3A%2F%2Fsdcdre.pdadkdedia.at%2Fdddio%2Fimg%2Fthumbnails%2Foriginal%2F%C3%96ffnungszeiten+Test-638.jpg
01-29 16:40:36.218: W/System.err(15131):    at java.net.URL.<init>(URL.java:178)
01-29 16:40:36.218: W/System.err(15131):    at java.net.URL.<init>(URL.java:127)
01-29 16:40:36.218: W/System.err(15131):    at com.peak.media.HomeActivityNewViewPager$FirstDownloadFileFromURL.doInBackground(HomeActivityNewViewPager.java:2478)
01-29 16:40:36.218: W/System.err(15131):    at com.peak.media.HomeActivityNewViewPager$FirstDownloadFileFromURL.doInBackground(HomeActivityNewViewPager.java:1)
01-29 16:40:36.218: W/System.err(15131):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-29 16:40:36.218: W/System.err(15131):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-29 16:40:36.218: W/System.err(15131):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-29 16:40:36.218: W/System.err(15131):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-29 16:40:36.218: W/System.err(15131):    at java.lang.Thread.run(Thread.java:856)

编码后我需要上面的结果。我不知道上面的网址使用了哪种编码。

String newurl=URLEncoder.encode(url,"UTF-8");

转换后,我使用UTF-8

获得了以下网址

[HTTPS%3A%2F%2Fsddde.psdfma.co%2Fstudio%2Fimg%2Fthumbnails%2Foriginal%2F%C3%96ffnungszeiten +试验638.jpg] [2]

3 个答案:

答案 0 :(得分:1)

因为空间进入网址Ravi Thapliyal回答不对,否则是对的

对我来说,下面的工作正在进行中

String ALLOWED_URI_CHARS = "@#&=*+-_ .,:!?()/~'%"; 
                    String spaceurl = Uri.encode(f_url[0], ALLOWED_URI_CHARS);
                    String newurl=spaceurl.replaceAll(" ", "%20");

答案 1 :(得分:0)

使用URL类来帮助拆分URL字符串并创建URI。多参数化URI构造函数会负责为您编码网址,与URLEncoder不同,这些空格会正确转换为%20而不是+

URL url = new URL(
    "http://example.com/studio/img/thumbnails/original/Öffnungszeiten Test-638.jpg"
);
try {
    String encURL = new URI(url.getProtocol(),
            url.getHost(), url.getPath(), null).toASCIIString();
    System.out.println(encURL);
} catch (URISyntaxException e) {
    e.printStackTrace();
}

输出:

http://example.com/studio/img/thumbnails/original/%C3%96ffnungszeiten%20Test-638.jpg

答案 2 :(得分:0)

URI uri = new URI("https",
                "sdcdre.deadmddia.co",
                "/studio/img/thumbnails/original/sfsnungszeiten Test-638.jpg",
                null,
                null);
uri.toASCIIString();