原文:
https://www.2cto.com/kf/201707/653916.html
1.布局,上一讲activity_main代码中添加 :
<button android:id="@+id/ok_post_file" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="上传文件">
<textview android:id="@+id/post_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="0">
<progressbar android:id="@+id/post_progress" android:layout_width="match_parent" android:layout_height="wrap_content" android:max="100">
</progressbar></textview></button>
2.OkHttpUtil新增上传文件方法:
public static void postFile(String url, final ProgressListener listener, Callback callback, File...files){
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
Log.i("huang","files[0].getName()=="+files[0].getName());
//第一个参数要与Servlet中的一致
builder.addFormDataPart("file",files[0].getName(), RequestBody.create(MediaType.parse("application/octet-stream"),files[0]));
MultipartBody multipartBody = builder.build();
Request request = new Request.Builder().url(url).post(new ProgressRequestBody(multipartBody,listener)).build();
okHttpClient.newCall(request).enqueue(callback);
}
3.ProgressRequestBody是自定义RequestBody类,用来监听进度:
public class ProgressRequestBody extends RequestBody {
public static final int UPDATE = 0x01;
private RequestBody requestBody;
private ProgressListener mListener;
private BufferedSink bufferedSink;
private MyHandler myHandler;
public ProgressRequestBody(RequestBody body, ProgressListener listener) {
requestBody = body;
mListener = listener;
if (myHandler==null){
myHandler = new MyHandler();
}
}
class MyHandler extends Handler {
//放在主线程中显示
public MyHandler() {
super(Looper.getMainLooper());
}
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case UPDATE:
ProgressModel progressModel = (ProgressModel) msg.obj;
if (mListener!=null)mListener.onProgress(progressModel.getCurrentBytes(),progressModel.getContentLength(),progressModel.isDone());
break;
}
}
}
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() throws IOException {
return requestBody.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
if (bufferedSink==null){
bufferedSink = Okio.buffer(sink(sink));
}
//写入
requestBody.writeTo(bufferedSink);
//刷新
bufferedSink.flush();
}
private Sink sink(BufferedSink sink) {
return new ForwardingSink(sink) {
long bytesWritten = 0L;
long contentLength = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
if (contentLength==0){
contentLength = contentLength();
}
bytesWritten += byteCount;
//回调
Message msg = Message.obtain();
msg.what = UPDATE;
msg.obj = new ProgressModel(bytesWritten,contentLength,bytesWritten==contentLength);
myHandler.sendMessage(msg);
}
};
}
}
4.在MainActivity添加上传按钮点击事件,代码如下:
File file = new File(basePath + "/1.mp4");
String postUrl = "https://192.168.0.104:8080/OkHttpServer/UploadFileServlet";
OkHttpUtil.postFile(postUrl, new ProgressListener() {
@Override
public void onProgress(long currentBytes, long contentLength, boolean done) {
Log.i(TAG, "currentBytes==" + currentBytes + "==contentLength==" + contentLength + "==done==" + done);
int progress = (int) (currentBytes * 100 / contentLength);
post_progress.setProgress(progress);
post_text.setText(progress + "%");
}
}, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null) {
String result = response.body().string();
Log.i(TAG, "result===" + result);
}
}
}, file);