添加依赖
implementation 'io.reactivex.rxjava2:rxjava:2.2.10'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.6.0'
接口文档
参见:https://sm.ms/doc/
第1步:创建Retrofit请求接口
public interface MainService {
@Multipart
@POST("https://sm.ms/api/upload")
@Headers({"User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"})
Observable<Result> uploadImage(@Part MultipartBody.Part filePart, @Part("format") RequestBody format);
}
第2步:使用Retrofit请求网络
/**
* 使用Retrofit上传图片
*/
public void uploadImageByRetrofit(String path) throws Exception {
// 创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://sm.ms/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
// 构建第一个请求参数
MainService service = retrofit.create(MainService.class);
// 构建接口请求参数
MediaType fileType = MediaType.parse("application/octet-stream");
File file = new File(path); // 要上传的文件对象
// 文件名中包含中文时,必须进行URL编码
String fileName = URLEncoder.encode(file.getName(), "UTF-8");
RequestBody requestBody = RequestBody.create(fileType, file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("smfile", fileName, requestBody);
// 构建第二个请求参数
MediaType formatType = MediaType.parse("text/plain");
RequestBody format = RequestBody.create(formatType, "json");
// 开始请求服务器
Observable<Result> observable = service.uploadImage(filePart, format);
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Result>() {
@Override
public void onSubscribe(Disposable d) {
// 开始请求
}
@Override
public void onNext(Result result) {
// 请求成功
System.out.println("onNext "+result.getData().getUrl());
}
@Override
public void onError(Throwable e) {
// 请求失败
System.out.println("onError " + e.getMessage());
}
@Override
public void onComplete() {
}
});
}
网友评论