android中使用URL读取网络资源

URL(Uniform Resource Locator)对象代表统一资源定位器,它是指向互联网“资源”的指针。

使用URL读取网络资源:

import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;

public class MainActivity extends Activity {
    ImageView show;
    Bitmap bitmap;
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0x123) {
                System.out.println("handlerMsg");
                show.setImageBitmap(bitmap);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        show = (ImageView) findViewById(R.id.show);
        new Thread() {

            public void run() {
                try {
                    // System.out.println(url.toString());
                    System.out.println(666);
                    //网址应该是图片的下载链接;
                    URL url = new URL("http://dl.image.so.com/d?imgurl=http%3A%2F%2Fimg.tupianzj.com%2Fuploads%2Fallimg%2F160522%2F9-160522114S1.jpg&purl=http%3A%2F%2Fwww.tupianzj.com%2Fgaoxiao%2Fbiaoqing%2F20160522%2F50570_7.html&key=72e4826817");

                    System.out.println(url.toString());
                    InputStream is = url.openStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    handler.sendEmptyMessage(0x123);
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            };
        }.start();
    }

}

使用了URL访问了图片资源并进行了显示,其中URL应是相应图片资源的下载链接地址。

 注意在配置文件中需加入访问网络权限: <uses-permission android:name="android.permission.INTERNET"/>

posted on 2017-05-23 10:25  baorant  阅读(3137)  评论(0编辑  收藏  举报

导航