40. 网络加载框架Retrofit完成文件上传和下载
40.1 文件上传
服务接口
package com.dingjiaxiong.myretrofit;
import okhttp3.MultipartBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface UploadService {
@POST("post")
@Multipart
Call<ResponseBody> upload(@Part MultipartBody.Part file);
}
测试
package com.dingjiaxiong.myretrofit;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;
public class UploadFileUnitTest {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
UploadService uploadService = retrofit.create(UploadService.class);
@Test
public void uploadFileTest() throws IOException {
File file1 = new File("D:\\DingJiaxiong\\AndroidStudioProjects\\MyRetrofit\\app\\src\\test\\java\\com\\dingjiaxiong\\myretrofit\\1.txt");
MultipartBody.Part part = MultipartBody.Part.createFormData("file1","1.txt",
RequestBody.create(MediaType.parse("text/plain"), file1));
Call<ResponseBody> call = uploadService.upload(part);
System.out.println(call.execute().body().string());
}
}
40.2 下载文件
定义接口
@GET
Call<ResponseBody> download(@Url String url);
测试
@Test
public void downloadTest() throws IOException {
Response<ResponseBody> response = uploadService.download("https://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Fimg2.doubanio.com%252Fview%252Fgroup_topic%252Fl%252Fpublic%252Fp405103212.jpg%26refer%3Dhttp%253A%252F%252Fimg2.doubanio.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Dauto%3Fsec%3D1662383764%26t%3D295487a6d3e7dc65517a6fbf925d7164&thumburl=https%3A%2F%2Fimg1.baidu.com%2Fit%2Fu%3D203795108%2C2901021673%26fm%3D253%26fmt%3Dauto%26app%3D138%26f%3DJPEG%3Fw%3D890%26h%3D500")
.execute();
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = new FileOutputStream("D:\\DingJiaxiong\\download\\a.jpeg");
int len;
byte[] buffer = new byte[4096];
while((len = inputStream.read(buffer)) != -1){
fileOutputStream.write(buffer,0,len);
}
fileOutputStream.close();
inputStream.close();
}
运行
下载成功。
标签:retrofit2,okhttp3,Part,40,download,import,Retrofit,加载 From: https://www.cnblogs.com/55zjc/p/16706554.html