SoFunction
Updated on 2025-03-03

Android OkHttp Post uploads files and carries parameters and examples for detailed explanation

Android OkHttp Post uploads files and carries parameters

Here I will sort out the method of OkHttp's post that also needs to carry the request parameters while uploading the file.

The version using OkHttp is as follows:

compile '.okhttp3:okhttp:3.4.1'

The code is as follows:

protected void post_file(final String url, final Map<String, Object> map, File file) {
    OkHttpClient client = new OkHttpClient();
    // form form upload     requestBody = new ().setType();
    if(file != null){
      // () It is the uploaded file type.      RequestBody body = (("image/*"), file);
      String filename = ();
      // The parameters are: Request key, file name, RequestBody      ("headImage", (), body);
    }
    if (map != null) {
      // The map contains the key and value required in the request.      for ( entry : ()) {
        (valueOf(()), valueOf(()));
      }
    }
    Request request = new ().url("Request Address").post(()).tag(context).build();
    // readTimeout("Request timeout" , time unit);    ().readTimeout(5000, ).build().newCall(request).enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
        ("lfq" ,"onFailure");
      }

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

        } else {
          ("lfq" ,() + " error : body " + ().string());
        }
      }
    });

  }

Here is what I mean, the addFormDataPart method is an encapsulation of the previous addPart method, so there is no need to configure the header or the like.

If it is just a simple Post carrying parameters, then use FormBody directly, the code is as follows:

 formBody = new ();
if (map != null) {
  for ( entry : ()) {
    ((()),(()));
  }
}

The above is just a sorting out the problems encountered in the project. If you need to know more, please check the analysis of the masters yourself.

Thank you for reading, I hope it can help you. Thank you for your support for this site!