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. MTK平台Android中常用的路径

    开机Logo的路径: bootable\bootloader\lk\dev\logo 开机Logo图片分辨率路径: device\rq\rq6735_35gt_b_l1\ProjectConfig.m ...

  2. KVM下windows虚拟机使用virtio驱动

    KVM下windows虚拟机默认disk使用的是Qemu IDE硬盘,网卡默认是rtl8139网卡.为了使kvm主机在相同的配置下,有更好的效率,可以将网卡和磁盘替换成virtio的驱动. windo ...

  3. javascript location对象

    location用于获取或设置窗体的URL,并且可以用于解析URL. location.[属性|方法] 1.location对象属性图示: 2.location 对象属性: 3.location 对象 ...

  4. Java中三种常见的注释(注解) Annotation

    Java为我们提供了三种Annotation方便我们开发. 1 Override-函数覆写注解 如果我们想覆写Object的toString()方法,请看下面的代码: class Annotation ...

  5. Sass入门:第二章

    1.Sass语法格式 假设有这样一段CSS代码: body{ font : 100% Helvetica , sans-serif; color : #333; } Sass最初的语法格式 $font ...

  6. SBT详解

    文章转载自http://beike.iteye.com/blog/1575296 SBT = (not so) Simple Build Tool,是scala的构建工具,与java的maven地位相 ...

  7. visual studio2013 apache cordova基于web的跨平台应用

    目前在研究微软的visual studio 2013开发跨平台的android.ios.windows phone.当然是基于html javascript css的web跨平台app. 在visua ...

  8. createElement创建

    定义和用法 createElement() 方法可创建元素节点. 此方法可返回一个 Element 对象. <script type="text/javascript"> ...

  9. POJ 2054 Color a Tree#贪心(难,好题)

    题目链接 代码借鉴此博:http://www.cnblogs.com/vongang/archive/2011/08/19/2146070.html 其中关于max{c[fa]/t[fa]}贪心原则, ...

  10. 浙大 pat 1007题解

    Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, ...