使用okhttp3实现多文件上传及表单数据一起上传

1 创建okhttpClient

  • 代码如下,上传文件设置超时时间30s
  OkHttpClient client = new OkHttpClient.Builder()
                        .writeTimeout(30, TimeUnit.SECONDS)
                        .build();

创建多文件上传的container

  • 设置文件传输的编码与类型
```
 MediaType MutilPart_Form_Data = MediaType.parse("multipart/form-data; charset=utf-8");
  • 为防止乱码,为其它表单数据设置格式
   try {

                    RequestBody bodyParams = RequestBody.create(MutilPart_Form_Data, JSON.toJSONString(params));
  • 创建requestBodyBuilder
    MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("keyVo", "", bodyParams);
  • 添加批量文件
 //循环添加文件
                    for (int i = 0; i < pathList.size(); i++) {
                        File file = new File(pathList.get(i));
                        requestBodyBuilder.addFormDataPart("files", file.getName(), RequestBody.create(MutilPart_Form_Data, new File(pathList.get(i))));
                    }
  • 创建requestBody并执行,返回结果
  RequestBody requestBody = requestBodyBuilder.build();
                    Request request = new Request.Builder()
                            .url(ConstBuild.BASE_URL + url)
                            .post(requestBody)
                            .build();
                             Response response = client.newCall(request).execute();
                             String responseStr=response.body().toString();
                             Log.w("result","返回结果"+responseStr);

完整代码如下

   /**
     * @param url
     * @param pathList
     * @throws Exception
     */
    public static void upLoadFiles(final String url, final String signPath, final Map params, final List pathList, final MyCallBack myCallBack) {
        x.task().run(new Runnable() {
            @Override
            public void run() {
                ToolLog.w("http", "url:\n" + url);
                ToolLog.w("http", "请求参数 params:\n" + params.toString());
                OkHttpClient client = new OkHttpClient.Builder()
                        .writeTimeout(30, TimeUnit.SECONDS)
                        .build();
                try {
                    MediaType MutilPart_Form_Data = MediaType.parse("multipart/form-data; charset=utf-8");
                    RequestBody bodyParams = RequestBody.create(MutilPart_Form_Data, JSON.toJSONString(params));
                    MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("keyVo", "", bodyParams);
                    //循环添加文件
                    for (int i = 0; i < pathList.size(); i++) {
                        File file = new File(pathList.get(i));
                        requestBodyBuilder.addFormDataPart("imgs", file.getName(), RequestBody.create(MutilPart_Form_Data, new File(pathList.get(i))));
                    }
                    RequestBody requestBody = requestBodyBuilder.build();
                    Request request = new Request.Builder()
                            .url( url)
                            .post(requestBody)
                            .build();
                    Response response = client.newCall(request).execute();
                    myCallBack.onSuccess(response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                    myCallBack.onError(new UnknownServiceException("服务器错误"), false);
                }
            }

        });
    }
  • MyCallBack
只是一个回调接口,大家可以自定义

你可能感兴趣的:(android)