1. 程式人生 > >android 利用OKhttp 上傳單張或者多張圖片

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);
          }
       });
    }
}