添加权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
添加依赖
implementation("com.squareup.okhttp3:okhttp:3.12.3")
示例代码
/**
* Okhttp上传图片(流)
*/
private void okHttpUploadImage() {
// 创建 OkHttpClient
OkHttpClient client = new OkHttpClient.Builder().build();
// 要上传的文件
File file = new File("/storage/emulated/0/Download/timg-4.jpg");
MediaType mediaType = MediaType.parse("image/jpeg");
// 把文件封装进请求体
RequestBody fileBody = RequestBody.create(mediaType, file);
// MultipartBody 上传文件专用的请求体
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM) // 表单类型(必填)
.addFormDataPart("smfile", file.getName(), fileBody)
.build();
Request request = new Request.Builder()
.url("https://sm.ms/api/upload")
.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0")
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
System.out.println(response.body().string());
} else {
System.out.println(response.code());
}
}
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
});
}
网友评论