主要方法
传递两个参数就可以了
protected void post_file(final String url,File file) {
OkHttpClient client = new OkHttpClient();
MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
if(file != null){
RequestBody body = RequestBody.create(MediaType.parse("mp4/*"),file);
String filename = file.getName();
requestBody.addFormDataPart("file",file.getName(),body).addFormDataPart("type","event");
}
}
Request request = new Request.Builder().url(url).post(requestBody.build()).tag(EventsReportedActivity.this).build();
// readTimeout("请求超时时间",时间单位);
client.newBuilder().readTimeout(5000,TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call,IOException e) {
Log.i("lfq","onFailure");
}
@Override
public void onResponse(Call call,Response response) throws IOException {
if (response.isSuccessful()) {
String str = response.body().string();
Log.i("post_file::",response.message() + ",body " + str);
} else {
Log.i("post_file::",response.message() + " error : body " + response.body().string());
}
}
});
}
调用
路径对应的mp4文件是真实存在的
File file = new File("/storage/emulated/0/DCIM/ZyfVideo/VID_20210316_175950.mp4");
post_file("url地址",file);