1. 程式人生 > >okHttp上傳圖片\下載圖片

okHttp上傳圖片\下載圖片

首先我們需要先匯入依賴,或者去看GitHub的官方文件找最新版:

implementation 'com.squareup.okhttp3:okhttp:3.11.0'

其次我們就需要加入許可權

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

一、佈局很簡單,就2個按鈕加一個圖片

<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/downLoad"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下載圖片"/>

    <Button
        android:id="@+id/upLoad"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="上傳圖片"/>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="55dp"/>
</LinearLayout>

二、MainActivity程式碼

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView mImageView;
    private String downLoadUrl = "https://10.url.cn/eth/ajNVdqHZLLAxibwnrOxXSzIxA76ichutwMCcOpA45xjiapneMZsib7eY4wUxF6XDmL2FmZEVYsf86iaw/";
    private String upLoadUrl = "https://www.718shop.com/sell/sell.m.picture.upload.do";

    //handler成功和失敗的標識
    private static final int SUCCESS = 0;
    private static final int FAILURE = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控制元件
        initView();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SUCCESS:
                    //拿到obj中的資料
                    byte[] bytes = (byte[]) msg.obj;
                    //使用BitmapFactory將位元組轉換成bitmap型別
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    //設定圖片
                    mImageView.setImageBitmap(bitmap);

                    break;
                case FAILURE:
                    Toast.makeText(MainActivity.this, "請求資料失敗", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    private void initView() {
        Button downLoad = findViewById(R.id.downLoad);
        Button upLoad = findViewById(R.id.upLoad);
        mImageView = findViewById(R.id.imageView);
        downLoad.setOnClickListener(this);
        upLoad.setOnClickListener(this);
    }

    //點選
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //下載
            case R.id.downLoad:
                downLoad();
                break;
                //上傳
            case R.id.upLoad:
                upLoad();
                break;
        }
    }


    //下載
    private void downLoad() {

        //建立okHttp
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(8, TimeUnit.SECONDS)
                .readTimeout(8, TimeUnit.SECONDS)
                .build();
        //建立request
        Request request = new Request.Builder()
                .url(downLoadUrl).build();

        //建立call
        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.sendEmptyMessage(FAILURE);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //將流轉換成位元組
                byte[] bytes = response.body().bytes();
                //獲取message物件
                Message message = mHandler.obtainMessage();
                //將位元組存入obj
                message.obj = bytes ;
                //設定一個標識
                message.what = SUCCESS;
                //傳送
                mHandler.sendMessage(message);
            }
        });


    }
	
	//這裡需要注意下我們圖片的路徑:
	/* 檔案儲存:應用程式可以把資料儲存在外儲存卡(sd卡),存放的路徑:/mnt/sdcard/檔名,可以放較的大資料
		注意:Android系統版本4.3之前路徑是/mnt/sdcard ,Android系統版本4.3之後storage/sdcard*/
    //上傳
    private void upLoad() {
        //建立檔案物件
        File file = new File(Environment.getExternalStorageDirectory() + "/Download" , "timg.jpg");
        //建立RequestBody封裝引數
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        //建立MultiparBody,給RequestBody進行設定
        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", "timg.jpg", fileBody)
                .build();
        //建立Request
        Request request = new Request.Builder()
                .url(upLoadUrl)
                .post(multipartBody)
                .build();
        //建立okHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(8, TimeUnit.SECONDS)
                .connectTimeout(8, TimeUnit.SECONDS)
                .writeTimeout(8,TimeUnit.SECONDS)
                .build();
        //建立call物件
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("wjh","upLoad 、  e=" + e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("wjh","upLoad 、  response = "+response.body().string());
            }
        });

    }


}