okhttp加载图片


第一步我们要在 build.gradle文件下导入OKHPPT的依赖库
compile 'com.squareup.okhttp3:okhttp:3.4.2'
 
  

public class MainActivity extends AppCompatActivity {
  private String path="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1527002323765&di=a5271ae1cba8945183d3a2326ea41e6a&imgtype=0&src=http%3A%2F%2Fwww.cd-auto.net%2Fupload%2Fnews%2Fa84bf7035c1b472b976e8a145f9ba5ff%2F201710130356363704.jpg";
    private Button jiaz;
    @SuppressLint("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){

                case 0:
                    byte[] obj = (byte[]) msg.obj;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(obj, 0, obj.length);
                    ing.setImageBitmap(bitmap);

                    break;
                case 1:

                    break;
            }

        }
    };
    private ImageView ing;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        jiaz = findViewById(R.id.jiazimg);
        ing = findViewById(R.id.img);
        jiaz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                OkHttpClient client = new OkHttpClient();
                final Request request = new Request.Builder().url(path).build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        byte[] bytes = response.body().bytes();
                        Message msg=new Message();
                        msg.obj=bytes;
                        msg.what=0;
                        handler.sendMessage(msg);


                    }
                });

            }
        });
        }
    }

你可能感兴趣的:(okhttp加载图片)