2 nana4ever nana4ever 于 2013.01.09 15:53 提问

Android中如何编码url字符串?

我想从URL中获取图片,再加载到imageView中。但是我不知道如何编码url字符串。请问如何编码url字符串?
我贴出URL和代码
URL: http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/%7BB690E93E-F7C9-48AF-B72A-BFF944FA6D4A%7D_104_9169.JPG

Code:

String link=URLEncoder.encode(urlStr);                    
bitmap=loadBitmap(link);

public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    try {
        InputStream in = new java.net.URL(url).openStream();
        bitmap = BitmapFactory.decodeStream(in);
    } catch (Exception e) {

    }        
    return bitmap;
}

3个回答

O_Casper_ne
O_Casper_ne   2013.01.09 17:38
已采纳

使用下面的代码可以从服务器中获取图像

String URL = "http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/%7BB690E93E-F7C9-48AF-B72A-BFF944FA6D4A%7D_104_9169.JPG"; 

private InputStream OpenHttpConnection(String urlString) throws IOException {
        InputStream in = null;
        int response = -1;
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");

        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();

            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }

private Bitmap DownloadImage(String URL) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);

            in.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            final String msg = e1.getMessage();
            handler.post(new Runnable() {  
                public void run() {  
                    Toast.makeText(getApplicationContext(), "" + msg, Toast.LENGTH_SHORT).show();  
                }  
            });
        }
        return bitmap;
    }
A328240784
A328240784   2013.01.09 16:13

....你首先看看in能不能把流写在sdcard上,看看下载下来的是不是图片。。。网络流市场有堵塞的情况,建议先下载下来

yongyong_21
yongyong_21   2013.01.10 13:40

我参考 How to display image from URL 创建过上面的例子,你可以参考下。

Csdn user default icon
上传中...
上传图片
插入图片