我想從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;
}