Java 从AndroidHttpClient迁移到URLConnection

Java 从AndroidHttpClient迁移到URLConnection,java,android,parse-platform,urlconnection,androidhttpclient,Java,Android,Parse Platform,Urlconnection,Androidhttpclient,我对这方面比较陌生,我一直在使用AndroidHttpClient来帮助通过解析将图像下载到我的应用程序。现在使用sdk23,我必须重写我的一些类。我的问题相当简单 让我们以以下代码为例,它什么都不做: new TwinPrimeSDK(getApplicationContext(), "12345678-1234-1234-1234-123456789012-1234567-123"); try { URLConnection httpConn = TPURLConne

我对这方面比较陌生,我一直在使用AndroidHttpClient来帮助通过解析将图像下载到我的应用程序。现在使用sdk23,我必须重写我的一些类。我的问题相当简单

让我们以以下代码为例,它什么都不做:

new TwinPrimeSDK(getApplicationContext(), "12345678-1234-1234-1234-123456789012-1234567-123");
    try {
        URLConnection httpConn = TPURLConnection.openConnection("your-URL");
    } catch (IOException e) {
        e.printStackTrace();
    }
“你的URL”指的是什么?通过Apache上的AndroidHttpClient,我从来不用为任何事情使用特定的URL。它只是起作用了

更新:

public class ImageLoader {

    // Last argument true for LRU ordering
    private Map<String, String> objectIdToUriMap = Collections.synchronizedMap(new LinkedHashMap<String, String>(10, 1.5f, true));

    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    // Handler to display images in UI thread
    Handler handler = new Handler();

    public ImageLoader(FileCache fileCache) {
        //fileCache = new FileCache(context);
        this.fileCache = fileCache;
        executorService = Executors.newFixedThreadPool(5);

        // need to re-evaluate where to do this as it is causing problems with not being able to download feed items as they are cleared from cache
        //clearCache();
        // only clear file cache, we're not using mem cache (every time we instantiate with a filecache)
        fileCache.clear();
    }


    public void DisplayImage(String url, ImageView imageView, ProgressBar progress) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
        }
        else {
            queuePhoto(url, imageView, progress);
            //imageView.setImageResource(stub_id);
            imageView.setVisibility(View.GONE);

            if(progress != null) {
                progress.setVisibility(View.VISIBLE);
            }
        }
    }

    private void queuePhoto(String url, ImageView imageView, ProgressBar progress) {
        PhotoToLoad p = new PhotoToLoad(url, imageView, progress);
        executorService.submit(new PhotosLoader(p));
    }

    // must be run in a thread
    private Bitmap getBitmap(String url) {
        File f = fileCache.getFile(url);

        Bitmap b = decodeFile(f);
        if (b != null) {
            return b;
        }

        // Download Images from the Internet
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is = conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            FeedUtils.CopyStream(is, os);
            os.close();
            conn.disconnect();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex) {
            ex.printStackTrace();
            if (ex instanceof OutOfMemoryError)
                memoryCache.clear();
            return null;
        }
    }

    public Uri getImageURIWithDownload(String url) {
        // try getting file from cache 1st
        File f = fileCache.getFile(url);
        if (f != null) {
            if(f.exists()) {
                return Uri.fromFile(f);
            }
        }

        // get bitmap from http (or cache, in fact)
        getBitmap(url);

        // try getting file again
        f = fileCache.getFile(url);
        return (f != null) ? Uri.fromFile(f) : null;
    }

    // Decodes image and scales it to reduce memory consumption
    // note. wda. doesn't use sample size (no scaling!)
    private Bitmap decodeFile(File f) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1 = new FileInputStream(f);
            BitmapFactory.decodeStream(stream1, null, o);
            stream1.close();

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            //o2.inSampleSize = scale;
            FileInputStream stream2 = new FileInputStream(f);
            Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // Task for the queue
    private class PhotoToLoad {
        public String url;
        public ImageView imageView;
        public ProgressBar progress;

        public PhotoToLoad(String u, ImageView i, ProgressBar p) {
            url = u;
            imageView = i;
            progress = p;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;

        PhotosLoader(PhotoToLoad photoToLoad) {
            this.photoToLoad = photoToLoad;
        }

        @Override
        public void run() {
            try {
                if (imageViewReused(photoToLoad)) { return; }

                Bitmap bmp = getBitmap(photoToLoad.url);
                //memoryCache.put(photoToLoad.url, bmp);

                if (imageViewReused(photoToLoad))  { return; }

                BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            } catch (Throwable th) {
                th.printStackTrace();
            }
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad) {
        String tag = imageViews.get(photoToLoad.imageView);

        if (tag == null || !tag.equals(photoToLoad.url)) {
            return true;
        }

        return false;
    }

    // Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;

        public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
            bitmap = b;
            photoToLoad = p;
        }

        public void run() {
            if (imageViewReused(photoToLoad)) { return; }

            if (bitmap != null) {
                photoToLoad.imageView.setImageBitmap(bitmap);
                photoToLoad.imageView.setVisibility(View.VISIBLE);
                if(photoToLoad.progress != null)
                    photoToLoad.progress.setVisibility(View.GONE);
            }
            else {}
                //photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }

}
公共类ImageLoader{
//LRU排序的最后一个参数为true
private Map ObjectedTourimap=Collections.synchronizedMap(新的LinkedHashMap(10,1.5f,true));
MemoryCache MemoryCache=新的MemoryCache();
文件缓存文件缓存;
private Map ImageView=Collections.synchronizedMap(新的WeakHashMap());
执行服务执行服务;
//在UI线程中显示图像的处理程序
Handler=newhandler();
公共图像加载器(文件缓存文件缓存){
//fileCache=新的fileCache(上下文);
this.fileCache=fileCache;
executorService=Executors.newFixedThreadPool(5);
//需要重新评估在何处执行此操作,因为这会导致无法下载源项的问题,因为它们已从缓存中清除
//clearCache();
//仅清除文件缓存,我们不使用mem缓存(每次使用文件缓存实例化时)
fileCache.clear();
}
public void DisplayImage(字符串url、ImageView、进度条进度){
put(imageView,url);
位图位图=memoryCache.get(url);
if(位图!=null){
设置图像位图(位图);
}
否则{
队列照片(url、图像视图、进度);
//setImageResource(存根id);
设置可见性(View.GONE);
如果(进度!=null){
progress.setVisibility(View.VISIBLE);
}
}
}
私有void队列照片(字符串url、ImageView、ImageView、ProgressBar进度){
PhotoToLoad p=新的PhotoToLoad(url、imageView、progress);
executorService.submit(新的PhotoLoader(p));
}
//必须在线程中运行
私有位图getBitmap(字符串url){
文件f=fileCache.getFile(url);
位图b=解码文件(f);
如果(b!=null){
返回b;
}
//从Internet下载图像
试一试{
位图=空;
URL imageUrl=新URL(URL);
HttpURLConnection conn=(HttpURLConnection)imageUrl.openConnection();
连接设置连接超时(30000);
连接设置读取超时(30000);
conn.setInstanceFollowRedirects(真);
InputStream is=conn.getInputStream();
OutputStream os=新文件OutputStream(f);
CopyStream(is,os);
os.close();
连接断开();
位图=解码文件(f);
返回位图;
}捕获(可丢弃的ex){
例如printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
返回null;
}
}
公共Uri getImageURIWithDownload(字符串url){
//尝试从缓存中获取文件
文件f=fileCache.getFile(url);
如果(f!=null){
如果(f.exists()){
返回Uri.fromFile(f);
}
}
//从http(实际上是缓存)获取位图
获取位图(url);
//再次尝试获取文件
f=fileCache.getFile(url);
return(f!=null)?Uri.fromFile(f):null;
}
//对图像进行解码和缩放以减少内存消耗
//注意.wda.不使用样本大小(无缩放!)
私有位图解码文件(文件f){
试一试{
//解码图像大小
BitmapFactory.Options o=新的BitmapFactory.Options();
o、 inJustDecodeBounds=true;
FileInputStream stream1=新的FileInputStream(f);
解码流(stream1,null,o);
stream1.close();
//找到正确的刻度值。它应该是2的幂。
所需的最终int_尺寸=70;
内部宽度=o.向外宽度,高度=o.向外高度;
int标度=1;
while(true){
如果(宽度\u tmp/2<要求的\u尺寸
||高度(tmp/2<所需尺寸)
打破
宽度_tmp/=2;
高度_tmp/=2;
比例*=2;
}
//用inSampleSize解码
BitmapFactory.Options o2=新的BitmapFactory.Options();
//o2.inSampleSize=刻度;
FileInputStream stream2=新的FileInputStream(f);
位图位图=BitmapFactory.decodeStream(stream2,null,o2);
stream2.close();
返回位图;
}catch(filenotfounde异常){
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
//队列的任务
私有类光电负载{
公共字符串url;
公共影像视图;
公共进步酒吧进步;
公共PhotoToLoad(字符串u、图像视图i、进度条p){
url=u;
imageView=i;
进展=p;
}
}
类photoloader实现可运行{
光电负载光电负载;
PhotoLoader(PhotoToLoad PhotoToLoad){
this.photoToLoad=photoToLoad;
}
@凌驾
公开募捐{
试一试{
if(imageViewReused(photoToLoad)){return;}
位图bmp=getBitmap(photoLoad.url);
//memoryCache.put(photoload.url,bmp);
if(imageViewReused(photoToLoad)){return;}
BitmapDisplayer bd=新的BitmapDisplayer(bmp,photoTo
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));