使用Okhttp网络请求下载图片到指定文件夹

   一.在module中添加依赖

   compile 'com.squareup.okhttp3:okhttp:3.6.0'


  二.设置布局


 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout 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"
     android:paddingBottom="@dimen/activity_vertical_margin"
     android:paddingLeft="@dimen/activity_horizontal_margin"
     android:paddingRight="@dimen/activity_horizontal_margin"
     android:paddingTop="@dimen/activity_vertical_margin"
     tools:context="com.zhiyuan3g.myokhttpupload.MainActivity">


     <Button
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="上传"
         android:id="@+id/button"
         android:layout_alignParentTop="true"
         android:layout_centerHorizontal="true"
         android:layout_marginTop="56dp" />

     <ImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/imageView"
         android:layout_centerVertical="true"
         android:layout_centerHorizontal="true" />
 </RelativeLayout>
 

  三.使用okhttp下载图片到指定文件夹

  OkHttpClient okHttpClient=new OkHttpClient();
  Request request=new Request.Builder()
        .get()
        .url("http://pic.qiantucdn.com/58pic/17/85/35/559de1de9b223_1024.jpg")
        .build();
  Call call=okHttpClient.newCall(request);
  call.enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {

      }

      @Override
      public void onResponse(Call call, Response response) throws IOException {
         //将响应数据转化为输入流数据
          InputStream inputStream=response.body().byteStream();
          //将输入流数据转化为Bitmap位图数据
          Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
          File file=new File("/mnt/sdcard/picture.jpg");
          file.createNewFile();
          //创建文件输出流对象用来向文件中写入数据
          FileOutputStream out=new FileOutputStream(file);
          //将bitmap存储为jpg格式的图片
          bitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
          //刷新文件流
          out.flush();
          out.close();
          Message msg=Message.obtain();
          msg.obj=bitmap;
          handler.sendMessage(msg);
      }
  });

 四.如果要把下载的图片显示出来,可以在主线程中添加自定义Handler内部类

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

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值