addFormDataPart方法是OKHttp3中FormBody.Builder的方法之一,用于向表单中添加数据。一般情况下,我们会在RequestBody中调用addFormDataPart方法,将键值对的形式数据添加到请求体中,以便发送给服务器。 RequestBodyrequestBody=newMultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("key1","value1").a...
// name:表单域代表了一个key,服务端通过key找到对应的文件 //addFormDataPart(String name,String filename,RequestBody body) //type: MediaType.parse("multipart/form-data"),上传文件时需要传递此参数 RequestBody requestBody = multipartBuilder .type(MultipartBuilder.FORM) .addFormDataPart("username", "...
"test").addFormDataPart("password","test").addFormDataPart("file","file.txt",RequestBody.create(MediaType.parse("application/octet-stream"),newFile("src/test/resources/test.txt"))).build();Request request=
privatevoidsendMultipart(){mOkHttpClient=newOkHttpClient();RequestBody requestBody=newMultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("title","wangshu").addFormDataPart("image",
.addFormDataPart("b.jpg",file2.getName(),requestBody2) .build(); Request request=newRequest.Builder() .post(multipartBody) .url("https://www.httpbin.org/post") .build();//准备好请求的Call对象Call call =okHttpClient.newCall(request); ...
传入文件路径,formData是与服务端的header约定,此处约定:name是文件名称 定义文件上传的执行方法doUpload: protectedintdoUpload(Stringurl){try{OkHttpClienthttpClient=OkHttpClientMgr.Instance().getOkHttpClient();call=httpClient.newCall(generateRequest(url));Responseresponse=call.execute();if(response.isSuccessfu...
OkHttpClientclient=newOkHttpClient();Filefile=newFile("path/to/file.jpg");RequestBodyrequestBody=newMultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file",file.getName(),RequestBody.create(MediaType.parse("image/jpeg"),file)).build();Requestrequest=newRequest.Builder().url...
=null){RequestBody fileBody=RequestBody.create(MediaType.parse("application/octet-stream"),f);builder.addFormDataPart("file",f.getName(),fileBody);}MultipartBody requestBody=builder.build();//构建请求Request request=newRequest.Builder().url(url)//地址.post(requestBody)//添加请求体.build();...
如果是上传图片,则MediaType为image/jpg,这里的jpg可以换成png等其他图片格式,另一部分是封装整个请求体,如果有多个文件要上传或者多个post请求key-value,则可以统一封装到RequestBody中,此时还需要指明请求Content-Type,即multipart/form-data,文件请求体可以通过addFormDataPart方法进行封装,最后将请求体传入OkHttp请求中...
OkHttpClient client = new OkHttpClient(); File file = new File("path/to/file"); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file)) .build();...