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. php MYSQL 一条语句中COUNT出不同的条件

    SELECT DISTINCT c.uid, count( 1 ) AS zongji, count( if( task_type = 'mobile', true, NULL ) ) AS mobi ...

  2. Python3与Python2的区别汇总

    1.print 在Python3.0  是一个函数,正确输入应该是:print (3x) 2.raw_input 在Python3.0改成input

  3. 工艺成型及仿真、铸造工艺及仿真ProCAST软件入门认识介绍

    视频源:技术邻 关键词:ProCAST.工艺成型及仿真.铸造工艺及仿真 简介:ProCAST 软件是由美国 USE 公司开发的铸造过程的模拟软件采用基于有限元(FEM)的数值计算和综合求解的方法,对铸 ...

  4. jquery.validationEngine

    引入库文件 <!DOCTYPE html> <head> <!--jQuery--> <script type="text/javascript&q ...

  5. CentOS7 安装 Mysql 服务

    我希望所有的软件包都用 rpm.yum 安装,这样卸载.升级.管理方便,可是自带的 yum 仓库里面没有 mysql-server 或者不是最新的,我需要安装MySQL官方的 yum 仓库, http ...

  6. Velocity China 2016 Web 性能与运维大会:构建快速、可扩展的弹性网站

    Velocity China 2016 Web 性能与运维大会是一场关于构建快速.可扩展的弹性网站所需要的Web性能.运维及开发运维的训练.大会将于2016年12月1日在北京拉开帷幕,此次大会被众多业 ...

  7. 为什么使用 SLF4J 而不是 Log4J 来做 Java 日志

    转自:为什么使用 SLF4J 而不是 Log4J 来做 Java 日志 英文原文:Why use SLF4J over Log4J for logging in Java 每个Java开发人员都知道日 ...

  8. java 读取excel文件(只读取xls文件)

    package com.sun.test; import java.io.BufferedInputStream;import java.io.File;import java.io.FileInpu ...

  9. POJ 1067 取石子游戏(威佐夫博弈)

    传送门 #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> ...

  10. CF 604C Alternative Thinking#贪心

    (- ̄▽ ̄)-* #include<iostream> #include<cstdio> #include<cstring> using namespace std ...