android网络编程之HttpUrlConnection的讲解--实现文件的断点上传
1、网络开发不要忘记在配置文件中添加访问网络的权限
<uses-permission android:name="android.permission.INTERNET"/>
2、网络请求、处理不能在主线程中进行,一定要在子线程中进行。因为网络请求一般有1~3秒左右的延时,在主线程中进行造成主线程的停顿,对用户体验来说是致命的。(主线程应该只进行UI绘制,像网络请求、资源下载、各种耗时操作都应该放到子线程中)。
3、Android端程序
public class MoreUploadActivity extends Activity {
private TextView mTvMsg;
private String result = "";
private long start = 0; // 开始读取的位置
private long stop = 1024 * 1024; // 结束读取的位置
private int times = 0; //读取次数
private long fileSize = 0; //文件大小
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_times_upload);
initView();
}
private void initView(){
mTvMsg = (TextView) findViewById(R.id.tv_upload);
try {
FileInputStream file = new FileInputStream(Environment.getExternalStorageDirectory().getPath() + "/aaaaa/baidu_map.apk");
fileSize = file.available();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Thread(uploadThread).start();
}
private Thread uploadThread = new Thread(){
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://192.168.23.1:8080/TestProject/MoreUploadTest");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setChunkedStreamingMode(51200);
connection.setUseCaches(false);
// 设置允许输出
connection.setDoOutput(true);
// 设置断点开始,结束位置
connection.setRequestProperty("Range", "bytes=" + start + "-" + stop);
String path = Environment.getExternalStorageDirectory().getPath() + "/aaaaa/baidu_map.apk";
RandomAccessFile file = new RandomAccessFile(path, "rw");
file.seek(start);
byte[] buffer = new byte[1024];
int count = 0;
OutputStream os = connection.getOutputStream();
if(fileSize > 1024*1024){
for(int i=0; i<1024 && count!=-1; i++){
count = file.read(buffer);
os.write(buffer, 0, count);
}
}else{
for(int i=0; i<(fileSize/1024)+1 && count!=-1; i++){
count = file.read(buffer);
os.write(buffer, 0, count);
}
}
os.flush();
os.close();
Log.e("ABC", connection.getResponseCode() + "");
if(connection.getResponseCode() == 200){
result += StringStreamUtil.inputStreamToString(connection.getInputStream()) + "\n";
}
start = stop + 1;
stop += 1024*1024;
fileSize -= 1024*1024;
Message msg = Message.obtain();
msg.what = 0;
uploadHandler.sendMessage(msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(connection != null){
connection.disconnect();
}
}
};
};
private Handler uploadHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what == 0){
if(times >= 8){
mTvMsg.setText(result);
}else{
times += 1;
new Thread(uploadThread).start();
mTvMsg.setText(result);
}
}
};
};
}
4、服务器端使用Servlet开发,这里只给出doPost()方法
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String range = request.getHeader("Range");
int start = Integer.parseInt(range.substring(6, range.indexOf("-")));
int stop = Integer.parseInt(range.substring(range.indexOf("-")+1, range.length())); RandomAccessFile file = new RandomAccessFile("F:/JavaWeb/TestProject/WebRoot/files/baidu.apk", "rw");
file.seek(start);
InputStream is = request.getInputStream();
byte[] buffer = new byte[1024];
int count = 0;
while((count=is.read(buffer)) != -1){
file.write(buffer, 0, count);
}
if(is != null){
is.close();
}
if(file != null){
file.close();
} response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("文件上传成功" + start + "-" + stop);
out.flush();
out.close();
}
5、最主要的就是一:设置断点setRequestProperty("Range", "bytes=0-1024"),获取断点request.getHeader("Range")
二:通过RandomAccessFile来读写文件
6、对于输出流的三个方法的对比:
os.write(byte[] buffer); 可能出现错误,因为你每次读取的数据小于等于1024,但你每次写入的数据仍然是1024, 对图片有一定影响,对安装包绝对是致命的影响。
os.write(int oneByte); 效率低
os.write(byte[] buffer, int byteOffset, int byteCount); 效率高,和第二个方法相比有一个数量级的差别(主观上看,有兴趣的可以测几下)。
7、参考博文:http://blog.sina.com.cn/s/blog_413580c20100wmr8.html
android网络编程之HttpUrlConnection的讲解--实现文件的断点上传的更多相关文章
- android网络编程之HttpUrlConnection的讲解--实现文件断点下载
1.没有实现服务器端,下载地址为网上的一个下载链接. 2.网络开发不要忘记在配置文件中添加访问网络的权限 <uses-permission android:name="android. ...
- android网络编程之HttpUrlConnection的讲解--上传大文件
1.服务器后台使用Servlet开发,这里不再介绍. 2.网络开发不要忘记在配置文件中添加访问网络的权限 <uses-permission android:name="android. ...
- android网络编程之HttpUrlConnection的讲解--POST请求
1.服务器后台使用Servlet开发,这里不再介绍. 2.网络开发不要忘记在配置文件中添加访问网络的权限 <uses-permission android:name="android. ...
- android网络编程之HttpUrlConnection的讲解--GET请求
1.服务器后台使用Servlet开发,这里不再介绍. 2.测试机通过局域网链接到服务器上,可以参考我的博客:http://www.cnblogs.com/begin1949/p/4905192.htm ...
- android网络编程之HttpUrlConnection的讲解--DownLoadManager基本用法
1.DownLoadManager是Android用系统服务(Service)的方式来优化处理长时间的下载操作的一个工具类.避免了我们去处理多线程,通知栏等等. 2.不要忘记添加权限 <uses ...
- Android 网络编程之HttpURLConnection运用
Android 网络编程之HttpURLConnection 利用HttpURLConnection对象,我们可以从网络中获取网页数据. 01 URL url = new URL("http ...
- android 网络编程之HttpURLConnection与HttpClient使用与封装
1.写在前面 大部分andriod应用需要与服务器进行数据交互,HTTP.FTP.SMTP或者是直接基于SOCKET编程都可以进行数据交互,但是HTTP必然是使用最广泛的协议. 本文并 ...
- Android网络编程之HttpClient运用
Android网络编程之HttpClient运用 在 Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们 ...
- 【Android实战】----基于Retrofit实现多图片/文件、图文上传
本文代码详见:https://github.com/honghailiang/RetrofitUpLoadImage 一.再次膜拜下Retrofit Retrofit不管从性能还是使用方便性上都非常屌 ...
随机推荐
- echarts 折柱混合图 (绑数据后)
html: <div class="flot-chart-content" id="flot-dashboard-chart"></div&g ...
- A- Bear and Five Cards(codeforces ROUND356 DIV2)
A. Bear and Five Cards time limit per test 2 seconds memory limit per test 256 megabytes input stand ...
- Json-lib用法
Json-lib用法 1.需要的jar包有一下几个,别的文章中没有xom这个jar包,但我的工程中如果没有这个包,那么,json数据转换为xml数据的程序中在执行XMLSerializer xmlSe ...
- HDU 5867 Water problem
处理出1-99的,之后的加上多少hundred和and即可.整百和一千的时候注意一下. #pragma comment(linker, "/STACK:1024000000,10240000 ...
- hadoop中,combine、partition、shuffle作用分别是什么?
combine和partition都是函数,中间的步骤应该只有shuffle! combine分为map端和reduce端,作用是把同一个key的键值对合并在一起,可以自定义的.combine函数把一 ...
- VMWARE player 如何让 win2012 guest os 支持HYPER-V
在 vm player 下安装了 win2012 r2, 但是启用 hyper-v的时候,提示不支持, 这时候要修改 Open the file Location for this Virtual M ...
- asp.net javascript客户端调用服务器端方法
如何用js调用服务器端方法.首先服务器端方法的格式如下 [System.Web.Services.WebMethod] public static void serverMethod(s ...
- POJ 3710 Christmas Game#经典图SG博弈
http://poj.org/problem?id=3710 (说实话对于Tarjan算法在搞图论的时候就没搞太懂,以后得找时间深入了解) (以下有关无向图删边游戏的资料来自论文贾志豪<组合游戏 ...
- rabbitmq(1)-入门
参考: documentation: https://www.rabbitmq.com/documentation.htmldemo: https://www.rabbitmq.com/getstar ...
- Python & virtualenv使用说明
virtualenv是virtual environment的缩写,可以创建独立的Python环境,用起来比较干净: 安装(已安装pip 或者 easy_install): 如果使用pip: pi ...