2 markdowneide markdowneide 于 2013.05.23 14:06 提问

从网上下载 JPEG 出现的问题

我使用下面的类来下载一个图像,发送的url是正确的,但是url.getContext() 每次都返回null。问题出在哪里呢?

package com.WasserSportLotse;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.Context;
import android.graphics.drawable.Drawable;
class ImageDownloader {
    private Drawable d;
     public ImageDownloader(Context ctx, String url, String saveFilename) {
        try {
            InputStream is = (InputStream) this.fetch(url);
            d = Drawable.createFromStream(is, "src");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public Drawable getImage(){
        return d;
    }
     public Object fetch(String address) throws MalformedURLException,IOException {
         URL url = new URL(address);
        Object content = url.getContent();
        return content;
    }
}

3个回答

yongyong_21
yongyong_21   2013.05.23 15:26
已采纳
private String path = "http://www.*YOURPATH.COM/SOMETHING*";
    private String file;
    private String url;
    public ImageDownloader(String file){
        this.file = URLEncoder.encode(file);
        url = path + this.file;
    }
    public Drawable getImage() throws IOException, MalformedURLException {
        return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), "name");
}
luhuajcdd
luhuajcdd   2013.05.23 14:50
public static Bitmap downloadBitmap(String url, DefaultHttpClient client){

  HttpResponse response = null;
  HttpGet get = new HttpGet(url);
  try {
      response = client.execute(get);
      return BitmapFactory.decodeStream(response.getEntity().getContent());
  } 
  catch (ClientProtocolException e1) {
      e1.printStackTrace();
  }
  catch (IllegalStateException e){
      e.printStackTrace();
  } 
  catch (IOException e1) {
      e1.printStackTrace();
  }

  return null;
}
wurenbi45
wurenbi45   2013.05.23 14:35

url.getContent()不是去访问这个url资源.

URL url = new URL("http://www.android.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
    finally {
     urlConnection.disconnect();
   }
 }
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!