使用OkHttpClient发送POST请求并传递FormData参数,可以按照以下步骤进行: 创建OkHttpClient实例: 首先需要创建一个OkHttpClient的实例,这个实例将用于执行所有的HTTP请求。 java OkHttpClient client = new OkHttpClient(); 构造RequestBody,指定为FormBody并添加参数: 使用FormBody.Builder来构建表单数据,并添加所需的...
RequestBodybody=newMultipartBody.Builder().setType(MultipartBody.FORM) .addFormDataPart("name","Tome") .addFormDataPart("from","China") .addFormDataPart("hobby","football") .addFormDataPart("image","logo-square.png", RequestBody.create(MEDIA_TYPE_PNG,newFile("website/static/logo-square.png...
addFormDataPart(String name,String filename,RequestBody body) //type: MediaType.parse("multipart/form-data"),上传文件时需要传递此参数 RequestBody requestBody = multipartBuilder .type(MultipartBuilder.FORM) .addFormDataPart("username", "dali") .addFormDataPart("password", "1234") .addFormData...
一般情况下,我们会在RequestBody中调用addFormDataPart方法,将键值对的形式数据添加到请求体中,以便发送给服务器。 RequestBodyrequestBody=newMultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("key1","value1").addFormDataPart("key2","value2").build(); 1. 2. 3. 4. 5. 上面的代码...
publicvoidpostSync(){//同步请求newThread(newRunnable() { @Overridepublicvoidrun() { OkHttpClient okHttpClient=newOkHttpClient(); FormBody formBody=newFormBody.Builder() .add("a","1") .add("b","2") .build(); Request request=newRequest.Builder() ...
("password","admin")/第一个双引号是键值对的键,第二个是值.addFormDataPart("myfile","1.png",/第二个参数这里可以换成设置好的路径filepath如下行代码所示/RequestBody.create(MediaType.parse("application/octet-stream"),file))/.addFormDataPart("myfile",filepath,RequestBody.create(MediaType.parse...
如果是上传图片,则MediaType为image/jpg,这里的jpg可以换成png等其他图片格式,另一部分是封装整个请求体,如果有多个文件要上传或者多个post请求key-value,则可以统一封装到RequestBody中,此时还需要指明请求Content-Type,即multipart/form-data,文件请求体可以通过addFormDataPart方法进行封装,最后将请求体传入OkHttp请求中...
=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();...
protectedRequestgenerateRequest(Stringurl){// 构造上传请求,模拟表单提交文件StringformData=String.format("form-data;name=file; filename=%s",FileUtil.pickFileNameFromPath(fileInfo.filePath));FileProgressRequestBodyfilePart=newFileProgressRequestBody(newFile(fileInfo.filePath),"application/octet-stream",thi...
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image ...