【已解决】 OKHTTP编程中返回码显示成功,但多文件上传失败了
private void okhttpPostMutipleFile() {
@SuppressLint("SdCardPath") File fileJpg1 = new File("/sdcard/Download/browser/218(1).jpg");
@SuppressLint("SdCardPath") File fileJpg2 = new File("/sdcard/Download/browser/218(2).jpg");
@SuppressLint("SdCardPath") File fileJpg3 = new File("/sdcard/Download/browser/218(3).jpg");
if(!fileJpg1.exists()){
Log.v(TAG,fileJpg1.getName() + " does not exist");
}
else if(!fileJpg2.exists()){
Log.v(TAG,fileJpg2.getName() + " does not exist");
}
else if(!fileJpg3.exists()){
Log.v(TAG,fileJpg3.getName() + " does not exist");
}
else{
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(5000,TimeUnit.MILLISECONDS)
.build();
MediaType mediaType = MediaType.parse("image/jpeg");
RequestBody fileBody1 = RequestBody.create(fileJpg1,mediaType);
RequestBody fileBody2 = RequestBody.create(fileJpg2,mediaType);
RequestBody fileBody3 = RequestBody.create(fileJpg3,mediaType);
// 由于是上传文件,使用的不再是RequestBody.create构建,而是MultipartBody.Builder
// addFormDataPart有仨参数:文件key值,文件名字,以及文件体
RequestBody requestBody = new MultipartBody.Builder()
.addFormDataPart("file",fileJpg1.getName(),fileBody1)
.addFormDataPart("file",fileJpg2.getName(),fileBody2)
.addFormDataPart("file",fileJpg3.getName(),fileBody3)
.build();
Request request = new Request.Builder()
.url(BASE_URL + "/files/upload")
.post(requestBody)
.build();
Call postSingleFileTask = okHttpClient.newCall(request);
postSingleFileTask.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.v(TAG,"Error ==> " + e.toString());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
int responseCode = response.code();
Log.v(TAG,"responseCode ==> " + responseCode);
if(responseCode == HttpURLConnection.HTTP_OK){
String dataReturned = Objects.requireNonNull(response.body()).string();
Log.v(TAG,"dataReturned ==> " + dataReturned);
}
}
});
}
}
Log图片:

已解决,参数问题,key值没改