Android HttpUrlConnection的使用(二)

  HttpUrlConnection主要用于网络传输当中,前面已经提及到了使用HttpUrlConnection来加载一个网站,这里我记录一下:用它在网络上下载一张图片并且加载到imageview当中。我们需要注意的是:当前很多网站上的图片传输的模式主要分两种:1.一是加密传输,使用HttpsUrlConnection进行链接;2.而是非加密传输,使用HttpUrlConnection来传输。代码如下(非加密传输):

<LinearLayout 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"
    tools:context="com.example.android_http2.MainActivity" >
    <ImageView 
        android:layout_gravity="center"
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>

  首先创建了一个MainActivity类,来对ui进行更新的操作。

package com.example.android_http2;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;

public class MainActivity extends Activity {
    private ImageView imageview = null;
    private Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageview = (ImageView) findViewById(R.id.imageview);
        new HttpThread("http://img.mp.itc.cn/upload/20160416/5cbd639a2bbf41ffa68147df01254444_th.jpg", imageview, handler).start();
    }

}

  其次,创建一个线程类,来进行异步下载的功能。将网络上的代码先下载到本地上去,然后在用handler来通知主线程更新ui。

package com.example.android_http2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;

public class HttpThread extends Thread{
    private String url = null;
    private ImageView imageview = null;
    private Handler handler = null;
    public HttpThread (String url, ImageView imageview, Handler handler)
    {
        this.handler = handler;
        this.imageview = imageview;
        this.url = url;
    }
    public void run() {
        HttpURLConnection httpurlconnection = null;
        try {
            URL url = new URL(this.url);
            httpurlconnection = (HttpURLConnection) url.openConnection();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        InputStream in = null;
        try {
            httpurlconnection.setReadTimeout(5000);
            //允许获得输入流
            httpurlconnection.setDoInput(true);
            in = httpurlconnection.getInputStream();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        FileOutputStream out = null;
        File downfile = null;
        //判断当前的内存卡是否可以用
        Log.i("main", "我进来没1?");
        File file = null;
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
        {
            Log.i("main", "我进来没?");
            file = new File(Environment.getExternalStorageDirectory().toString() + File.separator + "imageviewdown" + File.separator + "image.jpg");
            if(!file.getParentFile().exists())
            {
                file.getParentFile().mkdirs();
                
            }
            else if(!file.exists())
            {
                Log.i("main", "我进来没?  62");
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            try {
                out = new FileOutputStream(file);
            } catch (FileNotFoundException e) {
                Log.i("main", "异常没?");
                e.printStackTrace();
            }
        }
        byte buff[] = new byte[2 * 1024];
        int len = 0;
        try {
            while((len = in.read(buff)) != -1)
            {
                out.write(buff, 0,len);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //将下载在本地的图片加载在一个bitmap当中来
        final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        Log.i("main", file.getAbsolutePath());
        //通知主线程来更新ui
        handler.post(new Runnable() {
            public void run() {
                imageview.setImageBitmap(bitmap);
            }
        });
    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,967评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,193评论 4 61
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,306评论 19 139
  • 作为历史上唯一一个被判死刑的才女,王小波在《寻找无双》里讲过,只有27岁的鱼玄机是死的兴高采烈的。 也难怪。 刚出...
    东方垚阅读 2,962评论 2 2
  • 1、我是一个心软的人 2、我是一个不懂得拒绝别人,容易妥协的的人 3、我是一个在乎别人感受的人 4、我是一个自卑的...
    沈乘三阅读 7,666评论 0 0