OkHttpClient 加載網絡圖片

一、 簡單介紹

  1. HTTP是現代應用常用的一種交換數據和媒體的網絡方式,高效地使用HTTP能讓資源加載更快,節省帶寬。OkHttp是一個高效的HTTP客戶端,它有以下默認特性:
    (1)支持HTTP/2,允許所有同一個主機地址的請求共享同一個socket連接
    (2)連接池減少請求延時
    (3)透明的GZIP壓縮減少響應數據的大小
    (4)緩存響應內容,避免一些完全重複的請求

總之這是一個比較強大的封裝好的強求網絡的工具類。

  1. 使用OkHttpClient 加載圖片
    下載支持庫 implementation 'com.squareup.okhttp3:okhttp:3.10.0' ,可上官網查看最新的okhttp庫,官方地址
    https://github.com/square/okhttp
    ,不要忘記在清單文件中申請訪問網絡的權限以及其他另外需要的權限。
    <uses-permission android:name="android.permission.INTERNET" />

具體java代碼如下,異步get請求訪問網絡圖片:

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final int GET_IMG = 1001;
    private String url = "http://pic33.nipic.com/20131007/13639685_123501617185_2.jpg";
    private Button button;
    private ImageView image;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = findViewById(R.id.imageView);
        button = findViewById(R.id.but);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AsyncGet();
            }
        });

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if (message.what == GET_IMG){
                    byte[] picture = (byte[]) message.obj;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(picture,0,picture.length);
                    image.setImageBitmap(bitmap);     //主線程修改UI
                }
                return true;
            }
        });
    }

    private void AsyncGet() {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder().url(url).get().build();   //默認爲get請求
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG,"onFailure = " +e);
            }

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

                byte[] picture = response.body().bytes();
                Log.e(TAG,"response = " + picture);
                Message message = Message.obtain();
                message.what = GET_IMG;
                message.obj = picture;
                handler.sendMessage(message);
            }
        });
    }
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章