Android OkHttp Post上傳文件並且攜帶參數

OkHttp 的 post 在上傳文件的同時,也要攜帶請求參數的方法。

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

postman測試:
在這裏插入圖片描述

/**
     * 上傳文件
     */
    public void postFile() throws IOException {
        /**
         * 寫數據到文件中,只是模擬下,
         */
        File file = new File(getFilesDir(), "file-data.json");
        FileOutputStream fos = openFileOutput(file.getName(),MODE_PRIVATE);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
        writer.write("寫入文件!!!");
        writer.close();
        fos.close();
        /**
         * 上傳文件到服務器中
         */
        MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
        OkHttpClient client = new OkHttpClient();//獲取OkHttpClient實例

        MultipartBody.Builder requestBody=new MultipartBody.Builder().setType(MultipartBody.FORM);//文件和json參數共同上傳
        if (file!=null){//添加文件到form-data
            RequestBody body = RequestBody.create(MEDIA_TYPE_MARKDOWN, file);
            // 參數分別爲, 請求key ,文件名稱 , RequestBody
            requestBody.addFormDataPart("file",file.getName(),body);
        }
        //添加taskid 字段到form-data
        requestBody.addFormDataPart("taskid","7e44afffa884a7476acf77aa6bc083bb1b2aeaff");


        String uri = "http://10.10.20.39/platform/public/index.php/api/data/file";
        final Request request = new Request.Builder().url(uri).post(requestBody.build()).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, "文件上傳onFailure: "+e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i(TAG, "文件上傳onResponse: "+response.body().string());
            }
        });

實例2:

protected void post_file(final String url, final Map<String, Object> map, File file) {
    OkHttpClient client = new OkHttpClient();
    // form 表單形式上傳
    MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
    if(file != null){
      // MediaType.parse() 裏面是上傳的文件類型。
      RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
      String filename = file.getName();
      // 參數分別爲, 請求key ,文件名稱 , RequestBody
      requestBody.addFormDataPart("headImage", file.getName(), body);
    }
    if (map != null) {
      // map 裏面是請求中所需要的 key 和 value
      for (Map.Entry entry : map.entrySet()) {
        requestBody.addFormDataPart(valueOf(entry.getKey()), valueOf(entry.getValue()));
      }
    }
    Request request = new Request.Builder().url("請求地址").post(requestBody.build()).tag(context).build();
    // readTimeout("請求超時時間" , 時間單位);
    client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
        Log.i("lfq" ,"onFailure");
      }

      @Override
      public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
          String str = response.body().string();
          Log.i("lfq", response.message() + " , body " + str);

        } else {
          Log.i("lfq" ,response.message() + " error : body " + response.body().string());
        }
      }
    });

  }


如果只是單純的 Post 攜帶參數,那麼直接使用 FormBody ,代碼如下:

FormBody.Builder formBody = new FormBody.Builder();
if (map != null) {
  for (Map.Entry entry : map.entrySet()) {
    formBody.add(String.valueOf(entry.getKey()),String.valueOf(entry.getValue()));
  }
}

參考:
https://blog.csdn.net/anywayiknow/article/details/81215865

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章