okhttp下载图片

依赖,别忘记加权限Intetnet

compile 'com.squareup.okio:okio:1.13.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
xml

xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context="com.bwie.rikso.MainActivity">

    <Button
        android:text="下载图片"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:id="@+id/button"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true" />

    <ImageView
        android:id="@+id/imageview"
        android:paddingTop="40dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        />
RelativeLayout>
activity类

package com.bwie.rikso;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private final String IMAGE_URL = "http://cdnq.duitang.com/uploads/item/201505/20/20150520102944_CiL3M.jpeg";

    private static final int IS_SUCCESS = 1;
    private static final int IS_FAIL = 0;

    private Button button;
    private ImageView imageView;

    private OkHttpClient client;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case IS_SUCCESS:
                    byte[] bytes = (byte[]) msg.obj;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    imageView.setImageBitmap(bitmap);
                    break;
                case IS_FAIL:
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) this.findViewById(R.id.button);
        imageView = (ImageView) this.findViewById(R.id.imageview);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用异步get
                asyncGet();
                //使用同步get
  /*              new Thread(new Runnable() {
                    @Override
                    public void run() {
                        synchronizedGet();
                    }
                }).start();*/
            }
        });

    }


    /**
     * 异步get,直接调用
     */
    private void asyncGet() {
        client = new OkHttpClient();
        final Request request = new Request.Builder().get()
                .url(IMAGE_URL)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                Message message = handler.obtainMessage();
                if (response.isSuccessful()) {
                    message.what = IS_SUCCESS;
                    message.obj = response.body().bytes();
                    handler.sendMessage(message);
                } else {
                    handler.sendEmptyMessage(IS_FAIL);
                }
            }
        });
    }

    /**
     * 同步写法,需要放在子线程中使用
     */
    private void synchronizedGet() {
        client = new OkHttpClient();
        final Request request = new Request.Builder().get()
                .url(IMAGE_URL)
                .build();

        try {
            Response response = client.newCall(request).execute();
            Message message = handler.obtainMessage();
            if (response.isSuccessful()) {
                message.what = IS_SUCCESS;
                message.obj = response.body().bytes();
                handler.sendMessage(message);
            } else {
                handler.sendEmptyMessage(IS_FAIL);
            }

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

    }

}

你可能感兴趣的:(joker01)