android - (HttpURLConnection)从互联网下载图像

时间:2014-11-16 09:32:51

标签: android genymotion android-internet

我想创建一个简单的Android应用程序,从互联网上检索图像 活动代码如下所示:

import java.io.IOException;
import java.io.InputStream;

import android.support.v7.app.ActionBarActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;

public class BitmapDemo extends ActionBarActivity {
    //bikin objek image view nya
    ImageView imageview;

    private Bitmap downloadImage(String url){
        Bitmap bitmap = null;
        InputStream in = null;
        Koneksi koneksi = new Koneksi();  //class untuk koneksi nya

        try{
            in = koneksi.OpenHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        }
        catch(IOException ex){
            Toast.makeText(this, ex.getLocalizedMessage(),Toast.LENGTH_LONG).show();
            ex.printStackTrace();
        }

        return bitmap;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bitmap_demo);

        //download image nya
        //Bitmap bitmap = downloadImage("http://10.0.3.2/mp/tux2.jpeg");  //localhost
        Bitmap bitmap = downloadImage("http://infinitejest.wallacewiki.com/david-foster-wallace/images/a/ab/Nasa_Emblem.jpg");  //localhost
        //Bitmap bitmap = downloadImage("nama saya luki");  //localhost
        imageview = (ImageView)findViewById(R.id.imageview);
        imageview.setImageBitmap(bitmap);
    }

为了连接,我创建了一个名为Koneksi.java的类(在第22行的活动中调用

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

//import org.apache.http.HttpConnection;

public class Koneksi {
    public InputStream OpenHttpConnection(String urlString) throws IOException{
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        final URLConnection conn = url.openConnection();

        if(!(conn instanceof HttpURLConnection)){
            throw new IOException("String yang dimasukkan bukan alamat web");
        }

                try{
                    HttpURLConnection httpCon = (HttpURLConnection) conn;
                    httpCon.setAllowUserInteraction(false);
                    httpCon.setInstanceFollowRedirects(true);
                    httpCon.setRequestMethod("GET");
                    httpCon.connect();

                    //apakah respon berhasil
                    response = httpCon.getResponseCode();
                    if(response == HttpURLConnection.HTTP_OK){  //sama dengan 200 ga ya
                        in = httpCon.getInputStream();
                    }
                }

                catch(Exception ex){
                    //ex.printStackTrace();
                    throw new IOException("koneksi error");
                }

        return in; 
    }
}

当我执行应用程序时,Koneksi.java上的捕获抛出,说" koneksi错误"。我错过了什么吗?

注意:我已经添加" android.permission.ACCESS_NETWORK_STATE"还有" android.permission.INTERNET"在清单中

3 个答案:

答案 0 :(得分:1)

您已添加权限。精细。但是你需要创建AsyncTask来执行此操作。

您正尝试在主线程上访问网络。

将您的Koneksi类更改为AsyncTask:

private class Koneksi extends AsyncTask<String, Integer, String>  {

    protected String doInBackground(String... params) {
        //your code for downloading image    
    }

    protected void onPostExecute(String result) {
        //handle result
    }
}

将其命名为:

new Koneksi().execute(params);  //params is a String array of input if any.

希望这有帮助。

答案 1 :(得分:1)

快速简便的方法:

    public class MyRunnable implements Runnable{

    private String url;
    public MyRunnable (String _url){
        url=_url;
    }

    @Override
    public void run() {
        final Bitmap bitmap;
        InputStream in = null;
        Koneksi koneksi = new Koneksi();  //class untuk koneksi nya

        try{
            in = koneksi.OpenHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        }
        catch(IOException ex){
            ex.printStackTrace();
        }
        BitmapDemo.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                imageview = (ImageView) findViewById(R.id.imageview);
                imageview.setImageBitmap(bitmap);
            }
        });
    }
}

并在您的代码中:

private Bitmap downloadImage(String url){
    Thread t = new Thread(new MyRunnable(url));
    t.start();
}

答案 2 :(得分:0)

在Android中,您无法从主线程打开网络连接。 用户界面在主线程上运行,因此每个连接都会中断界面,并且在执行下载时您无法执行任何操作。

您必须构建一个辅助类,它在后台连接并在下载完成后进行回调。

见这里:Perform Network Operations on a Separate Thread