android 利用OKhttp 上传单张或者多张图片

没有废话,代码如下 

if (path.size() > 0) {//path存放imgurl的集合
   for (int i = 0; i < path.size(); i++) {
      OkHttpClient client = new OkHttpClient();
      MultipartBody.Builder builder = new 
         MultipartBody.Builder().setType(MultipartBody.FORM);
      File file = new File(path.get(i));
      if (file != null) {
          builder.addFormDataPart("file", file.getName(),           
          RequestBody.create(MediaType.parse("png"), file));
          //添加其他参数
          //builder.addFormDataPart("id", id);
       }
      MultipartBody multipartBody = builder.build();
      //构建请求
      final Request request = new Request.Builder()
             .url("www.baidu.com")//请求地址
             .post(multipartBody)//添加请求体参数
             .build();
      //请求回调
      Call call = client.newCall(request);
      call.enqueue(new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
            Log.e("TAG","上传失败"+e.getLocalizedMessage());
          }

          @Override
          public void onResponse(Call call, Response response) throws IOException {
             final String responseStr = response.body().string();
             Log.e("TAG","上传成功"+responseStr);
          }
       });
    }
}

 

你可能感兴趣的:(android 利用OKhttp 上传单张或者多张图片)