应用开发过程中经常需要进行文件上传功能开发,通过okhttp3.0可以快速集合完成文件上传的功能。
代码如下:
- OkHttpClient http = new OkHttpClient();
- MultipartBody.Builder mBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
- int i = 0;
- for(String filePath :filelist) {
- File file = new File(filePath);
- if (!file.exists()){
- Toast.makeText(MainActivity.this,"上传"+filePath+"文件不存在!", Toast.LENGTH_SHORT).show();
- continue;
- }
- String fileMimeType = getMimeType(file);
- //这里获取文件类型,方法自己定义
- MediaType mediaType = MediaType.parse(fileMimeType);
- RequestBody fileBody = RequestBody.create(mediaType, file);
- mBody.addFormDataPart("file" + i, file.getName(), fileBody);
- i++;
- }
- RequestBody requestBody = mBody.build();
- Request requestPostFile = new Request.Builder()
- .url("http://www.jianshu.com/")
- .post(requestBody)
- .build();
- ...
复制代码