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的讲解--实现文件的断点上传的更多相关文章

  1. android网络编程之HttpUrlConnection的讲解--实现文件断点下载

    1.没有实现服务器端,下载地址为网上的一个下载链接. 2.网络开发不要忘记在配置文件中添加访问网络的权限 <uses-permission android:name="android. ...

  2. android网络编程之HttpUrlConnection的讲解--上传大文件

    1.服务器后台使用Servlet开发,这里不再介绍. 2.网络开发不要忘记在配置文件中添加访问网络的权限 <uses-permission android:name="android. ...

  3. android网络编程之HttpUrlConnection的讲解--POST请求

    1.服务器后台使用Servlet开发,这里不再介绍. 2.网络开发不要忘记在配置文件中添加访问网络的权限 <uses-permission android:name="android. ...

  4. android网络编程之HttpUrlConnection的讲解--GET请求

    1.服务器后台使用Servlet开发,这里不再介绍. 2.测试机通过局域网链接到服务器上,可以参考我的博客:http://www.cnblogs.com/begin1949/p/4905192.htm ...

  5. android网络编程之HttpUrlConnection的讲解--DownLoadManager基本用法

    1.DownLoadManager是Android用系统服务(Service)的方式来优化处理长时间的下载操作的一个工具类.避免了我们去处理多线程,通知栏等等. 2.不要忘记添加权限 <uses ...

  6. Android 网络编程之HttpURLConnection运用

    Android 网络编程之HttpURLConnection 利用HttpURLConnection对象,我们可以从网络中获取网页数据. 01 URL url = new URL("http ...

  7. android 网络编程之HttpURLConnection与HttpClient使用与封装

    1.写在前面     大部分andriod应用需要与服务器进行数据交互,HTTP.FTP.SMTP或者是直接基于SOCKET编程都可以进行数据交互,但是HTTP必然是使用最广泛的协议.     本文并 ...

  8. Android网络编程之HttpClient运用

    Android网络编程之HttpClient运用 在 Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们 ...

  9. 【Android实战】----基于Retrofit实现多图片/文件、图文上传

    本文代码详见:https://github.com/honghailiang/RetrofitUpLoadImage 一.再次膜拜下Retrofit Retrofit不管从性能还是使用方便性上都非常屌 ...

随机推荐

  1. Python基础篇-day8

    本节目录1.抽象接口2.静态方法.类方法.属性方法3.类的特殊方法 3.1 __doc__ 表示类的描述信息(注释) 3.2 __module__ 和 __class__ 3.3 __init__ 构 ...

  2. JAVA: 接入YSDK遇到的问题

    JAVA后台接口: 1, 腾讯开放平台: http://wiki.open.qq.com/wiki/%E9%A6%96%E9%A1%B5 2,YSDK介绍,大概流程: http://wiki.open ...

  3. Linux使用rsync客户端与服务端同步目录进行备份

    一.服务端设置 1. 修改 server 端配置 # vi /etc/rsyncd.conf 修改: uid = nobody # 该选项指定当该模块传输文件时守护进程应该具有的uid.默认值为&qu ...

  4. 老司机的奇怪noip模拟T3-zhugeliang

    3. 诸葛亮(zhugeliang.cpp/c/pas )[问题描述]xpp 每天研究天文学研究哲学,对于人生又有一些我们完全无法理解的思考.在某天无聊学术之后, xpp 打开了 http://web ...

  5. Java JVM 多态(动态绑定)

    Java JVM 多态(动态绑定) @author ixenos 摘要:绑定.动态绑定实现多态.多态的缺陷.纯继承与扩展接口.向下转型与RTTI 绑定 将一个方法的调用和一个方法的主体关联起来,称作( ...

  6. poj 1142 Smith Numbers

    Description While skimming his phone directory in 1982, Albert Wilansky, a mathematician of Lehigh U ...

  7. phpstudy 相关配置

    在/etc/my.cnf中 添加 expire_logs_days=5 phpstudy add   list    del

  8. Linux下搭建ntp时间同步服务器

    1.ntpd软件安装(略过) 2.修改ntp.conf配置文件 vi /etc/ntp.conf 第一种配置:允许任何IP的客户机都可以进行时间同步将“restrict default kod nom ...

  9. ural 1203. Scientific Conference(动态规划)

    1203. Scientific Conference Time limit: 1.0 second Memory limit: 64 MB Functioning of a scientific c ...

  10. 10.按要求编写Java应用程序。 (1)创建一个叫做People的类: 属性:姓名、年龄、性别、身高 行为:说话、计算加法、改名 编写能为所有属性赋值的构造方法; (2)创建主类: 创建一个对象:名叫“张三”,性别“男”,年龄18岁,身高1.80; 让该对象调用成员方法: 说出“你好!” 计算23+45的值 将名字改为“李四”

    package com.hanqi.test; public class People { private String name,sex; private int age; private doub ...