Android Http基础:图片下载并显示和WebView的应用

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

复制代码
xmlns:tools="http://schemas.android.com/tools"
复制代码
android:layout_width="match_parent"
复制代码
android:layout_height="match_parent"
复制代码
android:paddingLeft="@dimen/activity_horizontal_margin"
复制代码
android:paddingRight="@dimen/activity_horizontal_margin"
复制代码
android:paddingTop="@dimen/activity_vertical_margin"
复制代码
android:paddingBottom="@dimen/activity_vertical_margin"
复制代码
tools:context=".MainActivity">
复制代码
<ImageView
复制代码
    android:id="@+id/image"
复制代码
    android:layout_width="fill_parent"
复制代码
    android:layout_height="wrap_content"></ImageView>
复制代码
<WebView
复制代码
    android:id="@+id/wedView"
复制代码
    android:layout_width="fill_parent"
复制代码
    android:layout_height="fill_parent"
复制代码
    android:layout_below="@id/image"></WebView>

MainActivity:


/**

  • 在Android上发送HTTP请求的方式一般有两种,HttpURLConnection和HttpClient
    */
    public class MainActivity extends ActionBarActivity {

    private WebView webView;

复制代码
private ImageView imageView;
复制代码
public static final int SHOW_WEDVIEW = 0;
复制代码
private Handler handler = new Handler();
复制代码
@Override
复制代码
protected void onCreate(Bundle savedInstanceState) {
复制代码
    super.onCreate(savedInstanceState);
复制代码
    setContentView(R.layout.activity_main);
复制代码
    webView = (WebView) findViewById(R.id.wedView);
复制代码
    imageView = (ImageView) findViewById(R.id.image);
复制代码
    //通过网络加载图片
复制代码
    new ImageThread("http://gb.cri.cn/mmsource/images/2013/02/22/35/14607758026320856623.jpg",imageView,handler).start();
复制代码
    //在WebView中显示百度主页
复制代码
    new HttpThread("http://www.baidu.com",webView,handler).start();
复制代码
}

}
ImageThread(加载图片的线程):


public class ImageThread extends Thread {

复制代码
//声明要传递的参数
复制代码
private String url;
复制代码
private ImageView imageView;
复制代码
private Handler handler;
复制代码
//创建构造方法,对参数进行初始化
复制代码
public ImageThread(String url, ImageView imageView, Handler handler) {
复制代码
    this.url = url;
复制代码
    this.imageView = imageView;
复制代码
    this.handler = handler;
复制代码
}
复制代码
@Override
复制代码
public void run() {
复制代码
    try {
复制代码
        //定义一个URL对象
复制代码
        URL httpUrl = new URL(url);
复制代码
        //获取HttpURLConnection的实例,表示到URL所引用的远程对象的连接
复制代码
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
复制代码
        //设置读取超时时间
复制代码
        connection.setReadTimeout(5000);
复制代码
        //设置请求方法,GET表示希望从服务器那里获取数据,而POST则表示提交数据给服务器
复制代码
        connection.setRequestMethod("GET");
复制代码
        //设置该URLConnection的doOutput请求头字段的值
复制代码
        connection.setDoInput(true);
复制代码
        //用时间作为下载的图片的文件名
复制代码
        String fileName = String.valueOf(System.currentTimeMillis());
复制代码
        File downloadFile = null;
复制代码
        InputStream inputStream = connection.getInputStream();
复制代码
        //要把文件写到SD卡,所以用FileOutputStream
复制代码
        FileOutputStream fileOutputStream = null;
复制代码
        //判断SD卡是否存在,存在就创建文件
复制代码
        if (Environment.getExternalStorageState().equals(
复制代码
                Environment.MEDIA_MOUNTED)) {
复制代码
            File parent = Environment.getExternalStorageDirectory();
复制代码
            downloadFile = new File(parent,fileName);
复制代码
            fileOutputStream = new FileOutputStream(downloadFile);
复制代码
        }
复制代码
        //创建一个2K的缓冲区
复制代码
        byte[] bytes = new byte[2 * 1024];
复制代码
        int length;
复制代码
        if (fileOutputStream != null) {
复制代码
            while ((length = inputStream.read(bytes)) != -1) {
复制代码
                fileOutputStream.write(bytes,0,length);
复制代码
            }
复制代码
        }
复制代码
        final Bitmap bitmap = BitmapFactory.decodeFile(downloadFile.getAbsolutePath());
复制代码
        //通过handler去更新UI
复制代码
        handler.post(new Runnable() {
复制代码
            @Override
复制代码
            public void run() {
复制代码
                imageView.setImageBitmap(bitmap);
复制代码
            }
复制代码
        });
复制代码
    } catch (MalformedURLException e) {
复制代码
        e.printStackTrace();
复制代码
    } catch (IOException e) {
复制代码
        e.printStackTrace();
复制代码
    }
复制代码
}

}
HttpThread(加载WebView的线程):


public class HttpThread extends Thread {

复制代码
//声明要传递的参数
复制代码
private String url;
复制代码
private WebView webView;
复制代码
private Handler handler;
复制代码
//创建构造方法,对参数进行初始化
复制代码
public HttpThread(String url, WebView webView, Handler handler) {
复制代码
    this.url = url;
复制代码
    this.webView = webView;
复制代码
    this.handler = handler;
复制代码
}
复制代码
@Override
复制代码
public void run() {
复制代码
    try {
复制代码
        //定义一个URL对象
复制代码
        URL httpUrl = new URL(url);
复制代码
        //获取HttpURLConnection的实例,表示到URL所引用的远程对象的连接
复制代码
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
复制代码
        //设置读取超时时间
复制代码
        connection.setReadTimeout(5000);
复制代码
        //设置请求方法,GET表示希望从服务器那里获取数据,而POST则表示提交数据给服务器
复制代码
        connection.setRequestMethod("GET");
复制代码
        final StringBuffer stringBuffer = new StringBuffer();
复制代码
        /*  getInputStream():返回该URLConnection对应的输入流,用于获取URLConnection响应的内容
相关推荐
你过来啊你2 小时前
Android Handler机制与底层原理详解
android·handler
RichardLai883 小时前
Kotlin Flow:构建响应式流的现代 Kotlin 之道
android·前端·kotlin
AirDroid_cn3 小时前
iQOO手机怎样相互远程控制?其他手机可以远程控制iQOO吗?
android·智能手机·iphone·远程控制·远程控制手机·手机远程控制手机
YoungHong19923 小时前
如何在 Android Framework层面控制高通(Qualcomm)芯片的 CPU 和 GPU。
android·cpu·gpu·芯片·高通
xzkyd outpaper3 小时前
Android 事件分发机制深度解析
android·计算机八股
DemonAvenger3 小时前
Go中UDP编程:实战指南与使用场景
网络协议·架构·go
努力学习的小廉4 小时前
深入了解linux系统—— System V之消息队列和信号量
android·linux·开发语言
2501_916007474 小时前
iOS 性能测试工具全流程:主流工具实战对比与适用场景
websocket·tcp/ip·http·网络安全·https·udp
阿维的博客日记4 小时前
HTTP/3.0的连接迁移使用连接ID来标识连接为什么可以做到连接不会中断
网络·网络协议·http
半路_出家ren4 小时前
第8章:应用层协议HTTP、SDN软件定义网络、组播技术、QoS
网络·网络协议·http·mpls·qos·sdn软件定义网络·组播技术