我有一个应用程序,我从服务器下载图像并在imageview中显示它们。这在大多数时间都有效,但并非总是如此。似乎它不起作用的时候是网址中有空格的时候。我得到的错误是
java.lang.RuntimeException:java.io.FileNotFoundException:
我已经尝试了许多不同的方法来尝试编码网址,但到目前为止还没有成功。
这是我正在使用的课程。
private URL url;
Bitmap bitmap;
public ImageDownloader() {
}//constructor
public Drawable getImage(String urlString) throws IOException{
Log.i("url", urlString);
url = new URL(urlString);
InputStream is = url.openStream();
Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is));
Drawable image = new BitmapDrawable(bitmap);
return image;
}//getImage
static class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
@Override
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int bytee = read();
if (bytee < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}
public Bitmap getBitmap(String urlString) {
try {
//String s = Uri.encode(urlString);
url = new URL(urlString);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-agent", "Mozilla/4.0");
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream in = null;
try {
in = conn.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap = BitmapFactory.decodeStream(in);
}
getImage和getBitmap都有相同的错误。
以下是我正在使用的网址示例。
答案 0 :(得分:6)
这是一个奇怪的。我尝试编码正常的方式,但我仍然得到相同的错误。我检查了正在发送的URL以及#34;%20&#34;的空间已被更改。最后,通过绝望,我决定将空间改为&#34;%20&#34;我自己而不是编码。这解决了这个问题。不是最优秀的解决方案,但它有效!
String url1 = json.getString("app_imagepath");
String url = url1.replace(" ", "%20");
答案 1 :(得分:2)
URL编码将字符转换为可以通过Internet传输的格式。例如,空格编码为%20。
答案 2 :(得分:0)
试试这段代码,
String songThumbUrl = "Image URL";
try {
URL thumbURL = new URL(songThumbUrl);
try {
URLConnection urlConnection = thumbURL.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
Bitmap bitmap = BitmapFactory.decodeStream(bufferedInputStream);
songThumbImageView.setImageBitmap(bitmap);
bufferedInputStream.close();
inputStream.close();
} catch (IOException ioe) {
System.out.println("My Exception :" + ioe);
ioe.printStackTrace();
}
} catch (MalformedURLException mue) {
System.out.println("My Exception :" + mue);
mue.printStackTrace();
}