OkHttp实现图片的上传和下载

布局文件

实现下载模块

 OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder().get().url(UrlPath).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
              handler.sendEmptyMessage(FAILURE);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                byte[] read = response.body().bytes();
                Message message = handler.obtainMessage();
                message.obj = read;
                message.what = RESPONSE;
                handler.sendMessage(message);
            }
        });

实现上传模块

  //上传的接口
        String url = "https://www.718shop.com/sell/sell.m.picture.upload.do";
        //创建上传文件

        File file = new File(Environment.getExternalStorageDirectory()+"/Download/", "jjj.jpg");
        //创建ReaquestBody封装参数
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"),file);
        //创建MultipartBody给requestBody进行设置
        MultipartBody  multipartBody =  new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image","jjj.jpg",requestBody)
                .build();
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        OkHttpClient Client = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .build();

        Call call = Client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("lsq","上传失败");
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.e("lsq","上传成功"+response.body().string());
                }
            });

你可能感兴趣的:(个人参考,android)