创建接口ServerApi
public interface MyServerApi {
@POST("/upload")
public upload(@Query("usrid") String usrid, @Body RequestBody pcmBody);
}
- 使用retrofit创建一个MyServerApi对象
Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl("http://192.168.1.20:8080").build();
MyServerApi myServerApi = retrofit.create(MyServerApi.class);
- 自定义一个RequestBody的子类FileRequestBody
/**
* author : Richile
* date : 2017/3/29
* email : ruichao1001@foxmail.com
*/
public class FileRequestBody extends RequestBody{
private final static String TAG = FileRequestBody.class.getSimpleName();
/* 上传文件的类型 */
private MediaType mediaType;
/* 需要上传的文件 */
private File file;
/* 已经发送的字节数 */
private long writen = 0L;
/**
* 构造FileRequestBody
* @param mediaType 上传文件的类型
* @param file 上传的文件
*/
public FileRequestBody(MediaType mediaType, File file) {
this.mediaType = mediaType;
this.file = file;
}
@Override
public long contentLength() throws IOException {
return file.length();
}
@Override
public MediaType contentType() {
return mediaType;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSource bufferedSource = Okio.buffer(Okio.source(file));
byte[] buffer = new byte[8192];
long len = 0;
/**
* 从文件一次读取8k字节,发送给服务器
*/
while((len = bufferedSource.read(buffer)) > 0){
sink.write(buffer, 0, (int) len);
writen += len;
/* 这里就可以写一个回调接口,用户监听进度 */
Log.d(TAG, "writeTo: progress=" + (int)((writen/(float)contentLength()) * 100) + "%");
}
}
}
然后就可以使用retrofit上传文件了
/* 创建一个用于传输文件的RequestBody,使用POST方式发送出去 */
FileRequestBody fileRequestBody = new FileRequestBody(MediaType.parse("audio/pcm;rate=16000"), pcmFile);
retrofit2.Call<UploadResult> call = smartServerApi.upload(usrid, fileRequestBody);
call.enqueue(new retrofit2.Callback<UploadResult>() {
@Override
public void onResponse(retrofit2.Call<UploadResult> call, retrofit2.Response<UploadResult> response) {
if(response.isSuccessful()){
UploadResult result = response.body();
}else{
Log.d(TAG, "Upload onResponse: " + response.code() + ":" + response.message());
}
}
@Override
public void onFailure(retrofit2.Call<UploadResult> call, Throwable t) {
Log.d(TAG, "Upload onFailure: " + t.getMessage());
}
});