先贴上MainActivity.java

package cn.edu.zafu.sample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast; import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response; import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit; import cn.edu.zafu.coreprogress.helper.ProgressHelper;
import cn.edu.zafu.coreprogress.listener.ProgressListener;
import cn.edu.zafu.coreprogress.listener.impl.UIProgressListener; public class MainActivity extends AppCompatActivity {
private static final OkHttpClient client = new OkHttpClient.Builder()
//设置超时,不设置可能会报异常
.connectTimeout(1000, TimeUnit.MINUTES)
.readTimeout(1000, TimeUnit.MINUTES)
.writeTimeout(1000, TimeUnit.MINUTES)
.build();
private Button upload,download;
private ProgressBar uploadProgress,downloadProgeress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
} private void initView() {
uploadProgress= (ProgressBar) findViewById(R.id.upload_progress);
downloadProgeress= (ProgressBar) findViewById(R.id.download_progress);
upload= (Button) findViewById(R.id.upload);
download= (Button) findViewById(R.id.download);
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
upload();
}
});
download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
download();
}
});
} private void download() {
//这个是非ui线程回调,不可直接操作UI
final ProgressListener progressResponseListener = new ProgressListener() {
@Override
public void onProgress(long bytesRead, long contentLength, boolean done) {
Log.e("TAG", "bytesRead:" + bytesRead);
Log.e("TAG", "contentLength:" + contentLength);
Log.e("TAG", "done:" + done);
if (contentLength != -1) {
//长度未知的情况下回返回-1
Log.e("TAG", (100 * bytesRead) / contentLength + "% done");
}
Log.e("TAG", "================================");
}
}; //这个是ui线程回调,可直接操作UI
final UIProgressListener uiProgressResponseListener = new UIProgressListener() {
@Override
public void onUIProgress(long bytesRead, long contentLength, boolean done) {
Log.e("TAG", "bytesRead:" + bytesRead);
Log.e("TAG", "contentLength:" + contentLength);
Log.e("TAG", "done:" + done);
if (contentLength != -1) {
//长度未知的情况下回返回-1
Log.e("TAG", (100 * bytesRead) / contentLength + "% done");
}
Log.e("TAG", "================================");
//ui层回调
downloadProgeress.setProgress((int) ((100 * bytesRead) / contentLength));
//Toast.makeText(getApplicationContext(), bytesRead + " " + contentLength + " " + done, Toast.LENGTH_LONG).show();
} @Override
public void onUIStart(long bytesRead, long contentLength, boolean done) {
super.onUIStart(bytesRead, contentLength, done);
Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_SHORT).show();
} @Override
public void onUIFinish(long bytesRead, long contentLength, boolean done) {
super.onUIFinish(bytesRead, contentLength, done);
Toast.makeText(getApplicationContext(),"end",Toast.LENGTH_SHORT).show();
}
}; //构造请求
final Request request1 = new Request.Builder()
.url("http://121.41.119.107:81/test/1.doc")
.build(); //包装Response使其支持进度回调
ProgressHelper.addProgressResponseListener(client, uiProgressResponseListener).newCall(request1).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.e("TAG", "error ", e);
} @Override
public void onResponse(Response response) throws IOException {
Log.e("TAG", response.body().string());
}
});
} private void upload() {
File file = new File("/sdcard/1.doc");
//此文件必须在手机上存在,实际情况下请自行修改,这个目录下的文件只是在我手机中存在。 //这个是非ui线程回调,不可直接操作UI
final ProgressListener progressListener = new ProgressListener() {
@Override
public void onProgress(long bytesWrite, long contentLength, boolean done) {
Log.e("TAG", "bytesWrite:" + bytesWrite);
Log.e("TAG", "contentLength" + contentLength);
Log.e("TAG", (100 * bytesWrite) / contentLength + " % done ");
Log.e("TAG", "done:" + done);
Log.e("TAG", "================================");
}
}; //这个是ui线程回调,可直接操作UI
final UIProgressListener uiProgressRequestListener = new UIProgressListener() {
@Override
public void onUIProgress(long bytesWrite, long contentLength, boolean done) {
Log.e("TAG", "bytesWrite:" + bytesWrite);
Log.e("TAG", "contentLength" + contentLength);
Log.e("TAG", (100 * bytesWrite) / contentLength + " % done ");
Log.e("TAG", "done:" + done);
Log.e("TAG", "================================");
//ui层回调
uploadProgress.setProgress((int) ((100 * bytesWrite) / contentLength));
//Toast.makeText(getApplicationContext(), bytesWrite + " " + contentLength + " " + done, Toast.LENGTH_LONG).show();
} @Override
public void onUIStart(long bytesWrite, long contentLength, boolean done) {
super.onUIStart(bytesWrite, contentLength, done);
Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_SHORT).show();
} @Override
public void onUIFinish(long bytesWrite, long contentLength, boolean done) {
super.onUIFinish(bytesWrite, contentLength, done);
Toast.makeText(getApplicationContext(),"end",Toast.LENGTH_SHORT).show();
}
}; //构造上传请求,类似web表单
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("hello", "android")
.addFormDataPart("photo", file.getName(), RequestBody.create(null, file))
.addPart(Headers.of("Content-Disposition", "form-data; name=\"another\";filename=\"another.dex\""), RequestBody.create(MediaType.parse("application/octet-stream"), file))
.build(); //进行包装,使其支持进度回调
final Request request = new Request.Builder().url("http://121.41.119.107:81/test/result.php").post(ProgressHelper.addProgressRequestListener(requestBody, uiProgressRequestListener)).build();
//开始请求
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.e("TAG", "error ", e);
} @Override
public void onResponse(Response response) throws IOException {
Log.e("TAG", response.body().string());
}
}); }
}

紧接着就是布局文件了

layout_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"> <ProgressBar
android:id="@+id/upload_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0"
/> <Button
android:id="@+id/upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Upload"/> <ProgressBar
android:id="@+id/download_progress"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0"
/> <Button
android:id="@+id/download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Download"/> </LinearLayout>

另外别忘了给配置清单文件添加权限

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

还有一个就是添加依赖了

dependencies {
compile 'cn.edu.zafu:coreprogress:0.0.3'
}

以下问题需要添加

 packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LGPL2.1'
}

源代码地址:https://github.com/newcaoguo/CoreProgress.git

Android使用OkHttp实现带进度的上传下载的更多相关文章

  1. Android okHttp网络请求之文件上传下载

    前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...

  2. PHP+ajaxForm异步带进度条上传文件实例

    在使用ajaxForm方法之前,首先需要安装form.js的插件,网上有: 一.首先说用法,ajaxForm可以接收0或1个参数,该参数可以是一个变量.一个对象或回调函数,这个对象主要有以下参数: v ...

  3. OkHttp 优雅封装 HttpUtils 之 上传下载解密

    曾经在代码里放荡不羁,如今在博文中日夜兼行,只为今天与你分享成果.如果觉得本文有用,记得关注我,我将带给你更多. 还没看过第一篇文章的欢迎移步:OkHttp 优雅封装 HttpUtils 之气海雪山初 ...

  4. android 请求网络 和 httpclient的使用上传下载

    访问网络最主要的也就是 http协议了. http协议很简单,但是很重要. 直接上代码了,里面都是1个代码块 代码块的,用哪一部分直接拷出去用就好了. 1.访问网络用 get 和 post  自己组拼 ...

  5. ajax利用html5新特性带进度条上传文件

    http://blog.csdn.net/pkgray/article/details/27591283 http://www.matlus.com/html5-file-upload-with-pr ...

  6. Android Studio中不能显示svn的上传下载两个图标同时version control为灰,不可点击

    最近在接触Android Studio,涉及到svn的配置,因为是先安装的svn,后安装的Android Studio,后边同事告诉我, Android Studio 的SVN安装与其他IDE有很大差 ...

  7. RxHttp 完美适配Android 10/11 上传/下载/进度监听

    1.前言 随着Android 11的正式发布,适配Android 10/11 分区存储就更加的迫切了,因为Android 11开始,将强制开启分区存储,我们就无法再以绝对路径的方式去读写非沙盒目录下的 ...

  8. Android开发中使用七牛云存储进行图片上传下载

    Android开发中的图片存储本来就是比较耗时耗地的事情,而使用第三方的七牛云,便可以很好的解决这些后顾之忧,最近我也是在学习七牛的SDK,将使用过程在这记录下来,方便以后使用. 先说一下七牛云的存储 ...

  9. Retrofit2文件上传下载及其进度显示

    序 前面一篇文章介绍了Retrofit2的基本使用,这篇文章接着介绍使用Retrofit2实现文件上传和文件下载,以及上传下载过程中如何实现进度的显示. 文件上传 定义接口 1 2 3 @Multip ...

随机推荐

  1. 网页爬虫--scrapy进阶

    本篇将谈一些scrapy的进阶内容,帮助大家能更熟悉这个框架. 1. 站点选取 现在的大网站基本除了pc端都会有移动端,所以需要先确定爬哪个. 比如爬新浪微博,有以下几个选择: www.weibo.c ...

  2. AngularJs——grunt神器的使用

    前面我们已经知道了如何安装grunt,本章节给各位道友介绍如何使用 grunt 的插件,grunt是重点在于如何配置使用 Gruntfile.js,官网上也有很多范例. 1,包装函数 module.e ...

  3. C# JArray与JObject 的使用 json [{}]

    C# JArray与JObject 的使用 STEP1.using Newtonsoft.Json.Linq; STEP2 如何获取json里的某个属性(节点)值,对其删改,新增 //2.1 数组用J ...

  4. HTML5——购物车

    简要代码: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w ...

  5. Webbench网站压力测试

      Webbench是有名的网站压力测试工具,能测试处在相同硬件上,不同服务的性能以及不同硬件上同一个服务的运行状况.webBech的标准测试可以向我们展示服务器的 两项 内容:每秒钟相应请求数和每秒 ...

  6. 原型图利器 – Mockplus的审阅功能

    Mockplus是一款简洁快速的原型图工具 (http://www.mockplus.cn),最近推出了审阅功能. 审阅,旨在解决团队项目原型设计中的沟通和协作的问题. 没有孤立的原型,更没有一次成型 ...

  7. Action+Service +Dao三层的功能划分

    来源:http://blog.csdn.net/inter_peng/article/details/41021727 1. Action/Service/DAO简介: Action是管理业务(Ser ...

  8. ansible 的组件inventory

    P44 Ansible 的默认的inventory的是一个静态的ini格式的文件/etc/ansible/hosts. 我们还可以通过ansible_hosts环境变脸指定或者运行ansible和an ...

  9. mysql-分页查询方案

    一.直接使用limit最简单查询方法: , 在中小数据量的情况下,这样的SQL足够用了,唯一需要注意的问题就是确保使用了索引. 随着数据量的增加,页数会越来越多,查看后几页的SQL就可能类似: , 言 ...

  10. Oracle创建DBLink的方法

    文章从http://blog.csdn.net/davidhsing/article/details/6408770拷贝过来的 1.如果需要创建全局 DBLink,则需要先确定用户有创建 dblink ...