安卓利用OKHttpClient访问服务器图片资源

public class HomeFragment extends BaseFragment {
   private static final String TAG=HomeFragment.class.getSimpleName();
   private TextView textView;
   private ImageView imageView;
   private ListView listView;

   private Handler handler = new Handler(){
       @Override
       public void handleMessage(@NonNull Message msg) {
           Bitmap bitmap = (Bitmap) msg.obj;
           imageView.setImageBitmap(bitmap);
       }
   };

    @Override
    public View initView() {
        imageView=new ImageView(mContext);
        Log.e(TAG,"主页视图被加载了");

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(Constants.IMAGES).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("error","请求失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = response.body().byteStream();
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                Message message = new Message();
                message.obj = bitmap;
                handler.sendMessage(message);
            }
        });

        return imageView;
    }

url为:http://localhost:8080/images/background_img.jpg

你可能感兴趣的:(Android,java,android)