程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> android-Android中如何編碼url字符串?

android-Android中如何編碼url字符串?

編輯:編程綜合問答
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;
}

最佳回答:


使用下面的代碼可以從服務器中獲取圖像

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;
    }
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved