android中的http通讯(2)

这篇博客介绍了如何在Android应用中实现通过HTTP通讯下载网络图片,并将其保存到本地,然后展示在应用中。首先,需要在AndroidManifest.xml中添加INTERNET和WRITE_EXTERNAL_STORAGE权限。接着,展示了XML布局文件和下载图片后的实际效果。
摘要由CSDN通过智能技术生成

功能:通过网络请求下载一张图片到本地展示

在AndroidManifest.xml文件中添加权限:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

xml布局文件

<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/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout><strong>
</strong>
MainActivity.java文件

package com.example.dd;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
public class MainActivity extends Activity {
    private ImageView contentImageView;
    private Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        new HttpConnection("http://h.hiphotos.baidu.com/image/pic/item/6c224f4a20a446239e8d311c9b22720e0cf3d70d.jpg",contentImageView,handler).start();
    }

    private void init(){
        contentImageView = (ImageView)findViewById(R.id.imageView1);
    }
}
HttpConnection.java文件

package com.example.dd;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.webkit.WebView;
import android.widget.ImageView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
 * Created by xiaoyuer on 2015/11/13.
 */
public class HttpConnection extends Thread{
    private String mUrl;
    private ImageView mImageView;
    private Handler mHandler;
    HttpConnection(String Url,ImageView imageView,Handler Handler)
        {
            this.mUrl = Url;
            this.mImageView = imageView;
            this.mHandler = Handler;
    }
    @Override
    public void run()
    {
        try {
            //构建url对象
            URL httpUrl = new URL(mUrl);
            //通过openConnection方法打开一个HttpURLConnection对象
            HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
            //设置请求超时,访问网页时可能没给我们应答,设置超时等待时间
            conn.setReadTimeout(5000);
            //设置访问请求方式
            conn.setRequestMethod("GET");

            //获得图片信息的输入流
            conn.setDoInput(true);
            InputStream in = conn.getInputStream();

            //先把图片下载到本地
            FileOutputStream out = null;
            File downloadFile = null;
            //把当前的时间设置为文件名,valueOf()把long类型转换为String类型
            String fileName = String.valueOf(System.currentTimeMillis());

            //如果sd卡有加载
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            {
                //获得sd卡的根目录
                File parent = Environment.getExternalStorageDirectory();
                //创建目录
                downloadFile= new File(parent,fileName);
                out = new FileOutputStream(downloadFile);
            }

            //创建缓冲区(2个字节大小)
            byte[] b = new byte[2*1024];
            int length;
            if(out != null){
                while((length = in.read(b)) != -1){
                    out.write(b,0,length);
                }
            }

            final Bitmap bitmap = BitmapFactory.decodeFile(downloadFile.getAbsolutePath());
            //读出文件之后,通过handler去更新UI
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    //把已经下载来图片的bitmap传递进来
                    mImageView.setImageBitmap(bitmap);
                }
            });


        }catch(MalformedURLException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}

效果图:


已经把美女图下载下来

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值