Android发送数据到服务器和多线程断点下载



# 使用httpUrlconnection方式把数据提交到服务器

基于http协议

get方式:组拼url 地址把数据组拼到url上 有大小限制 1kb(浏览器) 4kb(http协议)

post方式:post方式提交安全,没有大小限制

<!--more-->
get方式提交数据代码:
```
// 点击按钮 进行get方式提交数据
    public void click1(View v) {
        
        new Thread(){public void run() {
            

            try {
            //[2]获取用户名和密码
            String name = et_username.getText().toString().trim();
            String pwd = et_password.getText().toString().trim();
            //[2.1]定义get方式要提交的路径 小细节 如果提交中文要对name 和 pwd 进行一个urlencode 编码
            String path = "http://192.168.11.73:8080/login/LoginServlet?username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";
        
                //(1) 创建一个url对象 参数就是网址
                URL url = new URL(path);
                //(2)获取HttpURLConnection 链接对象
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //(3)设置参数 发送get请求
                conn.setRequestMethod("GET"); //默认请求 就是get 要大写
                //(4)设置链接网络的超时时间
                conn.setConnectTimeout(5000);
                //(5)获取服务器返回的状态码
                int code = conn.getResponseCode(); //200 代表获取服务器资源全部成功 206请求部分资源
                if (code == 200) {
                    //(6)获取服务器返回的数据 以流的形式返回
                    InputStream inputStream = conn.getInputStream();

                    
                    //(6.1)把inputstream 转换成 string
                    String content = StreamTools.readStream(inputStream);
                    
                    
                    //(7)把服务器返回的数据展示到Toast上 不能在子线程展示toast
                    showToast(content);
                    
                    
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        };}.start();
        
        
        
    }
```

post方式和get区别

[1] 路径不同http://192.168.11.73:8080/login/LoginServlet

[2]请求方式不同,post方式要自己组拼请求体的内容。post方式比get方式多两个头信息content-length和content-type。

[3]通过请求体的方式把数据传给服务器(以流的形式)

# httpclient方式把数据提交到服务器

[1]开源项目

[2]命名实现类一般以base,default,simple进行命名。

[3]对http请求的封装

使用httpclient进行get请求
```
    public void click1(View v) {
        
        new Thread(){public void run() {
            try {
                String name = et_username.getText().toString().trim();
                String pwd = et_password.getText().toString().trim();
                //[2.1]定义get方式要提交的路径 小细节 如果提交中文要对name 和 pwd 进行一个urlencode 编码
                    String path = "http://192.168.11.73:8080/login/LoginServlet?username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";
                    
                    //[3]获取httpclient实例
                    DefaultHttpClient client = new DefaultHttpClient();
                    //[3.1]准备get请求 定义 一个httpget实现
                    HttpGet get = new HttpGet(path);
                    
                    //[3.2]执行一个get请求
                    HttpResponse response = client.execute(get);
                    
                    //[4]获取服务器返回的状态码
                    int code = response.getStatusLine().getStatusCode();
                    if (code == 200) {
                        //[5]获取服务器返回的数据 以流的形式返回
                        InputStream inputStream = response.getEntity().getContent();
                        
                        //[6]把流转换成字符串
                     String content = StreamTools.readStream(inputStream);   
                    
                     //[7]展示结果
                        showToast(content);
                    }
                    
                    
                    
                    
                    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            
        };}.start();
        
        
        
    }
```

使用httpclient进行post请求

```
    public void click2(View v) {

        
    new Thread(){public void run() {
            
            try {
                //[2]获取用户名和密码
                String name = et_username.getText().toString().trim();
                String pwd = et_password.getText().toString().trim();
                String path = "http://192.168.11.73:8080/login/LoginServlet";
                
                //[3]以httpClient 方式进行post 提交
                DefaultHttpClient client = new DefaultHttpClient();
                //[3.1]准备post 请求
                HttpPost post = new HttpPost(path);

                //[3.1.0]准备parameters
                List<NameValuePair> lists = new ArrayList<NameValuePair>();
                //[3.1.1]准备 NameValuePair 实际上就是我们要提交的用户名 和密码 key是服务器key :username
                BasicNameValuePair nameValuePair = new BasicNameValuePair("username",name);
                BasicNameValuePair pwdValuePair = new BasicNameValuePair("password",pwd);
                //[3.1.3] 把nameValuePair 和 pwdValuePair 加入到集合中
                lists.add(nameValuePair);
                lists.add(pwdValuePair);
                
                //[3.1.3]准备entity
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(lists);
                
                //[3.2]准备post方式提交的正文 以实体形式准备 (键值对形式 )
                post.setEntity(entity);
                
                
                HttpResponse response = client.execute(post);
                //[4]获取服务器返回的状态码
                int code = response.getStatusLine().getStatusCode();
                if (code == 200) {
                    //[5]获取服务器返回的数据 以流的形式返回
                    InputStream inputStream = response.getEntity().getContent();
                    
                    //[6]把流转换成字符串
                 String content = StreamTools.readStream(inputStream);   
                
                 //[7]展示结果
                    showToast(content);
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            
            
            
            
        };}.start();
        
        
    }
    
    
```

# 开源项目把数据提交到服务器

asyncHttpClient

[1]ge方式提交数据

```
public void click1(View v) {
        
        String name = et_username.getText().toString().trim();
        String pwd = et_password.getText().toString().trim();
        //[2.1]定义get方式要提交的路径 小细节 如果提交中文要对name 和 pwd 进行一个urlencode 编码
    
        try {
            path = "http://192.168.11.73:8080/login/LoginServlet?username="+URLEncoder.encode(name, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8")+"";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
            
     //[3]使用开源项目进行get请求
     //[3.1]创建asynchttpclient
     AsyncHttpClient client = new AsyncHttpClient();
     //[3.2]进行get 请求
     client.get(path, new AsyncHttpResponseHandler() {
            //请求成功的回调方法
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                
                try {
                    Toast.makeText(getApplicationContext(), new String(responseBody,"gbk"), 1).show();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                
            }
            
            //请求失败
            @Override
            public void onFailure(int statusCode, Header[] headers,
                    byte[] responseBody, Throwable error) {
                
            }
        });
    
    
    
        
        
        
        
    }
```

[2]post方式提交数据

```
// [1]点击按钮 进行post方式提交数据
    public void click2(View v) {
        //[2]获取用户名和密码
        String name = et_username.getText().toString().trim();
        String pwd = et_password.getText().toString().trim();
        String path = "http://192.168.11.73:8080/login/LoginServlet";
        //[3.1]创建asynchttpclient
     AsyncHttpClient client = new AsyncHttpClient();
    
     //[3.1.0]准备请求体的内容
     RequestParams params = new RequestParams();
     params.put("username", name);
     params.put("password", pwd);
     //[3.2]进行post请求 params 请求的参数封装
     client.post(path, params, new AsyncHttpResponseHandler() {
            //请求成功 登录成功
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                try {
                    Toast.makeText(getApplicationContext(), new String(responseBody,"gbk"), 1).show();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            
            @Override
            public void onFailure(int statusCode, Header[] headers,
                    byte[] responseBody, Throwable error) {
                
            }
        });
        
        
        
    }
    

```

# 多线程下载步骤

![ 1 ] (http://ov4gdtmdv.bkt.clouddn.com/TIM%E6%88%AA%E5%9B%BE20180118191719.jpg)

每个线程下载的计算公式

![ 2 ] (http://ov4gdtmdv.bkt.clouddn.com/TIM%E6%88%AA%E5%9B%BE20180118192117.jpg)

# 多线程断点下载实例

```
public class MainActivity extends Activity {

    private EditText et_path;
    private EditText et_threadCount;
    private LinearLayout ll_pb_layout;
    private String path;
    private static int runningThread; //代表当前正在运行的线程
    private int threadCount;
    private List<ProgressBar> pbLists; //用来存进度条的引用
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // [1]找到我们关心的控件
        
        et_path = (EditText) findViewById(R.id.et_path);
        et_threadCount = (EditText) findViewById(R.id.et_threadCount);
        ll_pb_layout = (LinearLayout) findViewById(R.id.ll_pb);
        
        
        //[2]添加一个集合 用来存进度条的引用
        pbLists = new ArrayList<ProgressBar>();
        
    }

    //点击按钮实现下载的逻辑
    public void click(View v){
        
        //[2]获取下载的路径
        
        path = et_path.getText().toString().trim();
        
        //[3]获取线程的数量
        String threadCountt = et_threadCount.getText().toString().trim();
        //[3.0]先移除进度条 在添加
        ll_pb_layout.removeAllViews();
        
        threadCount = Integer.parseInt(threadCountt);
        pbLists.clear();
        for (int i = 0; i < threadCount; i++) {
        
            //[3.1]把我定义的item布局转换成一个view对象
            ProgressBar pbView = (ProgressBar) View.inflate(getApplicationContext(), R.layout.item, null);
            
            //[3.2]把pbView 添加到集合中
            pbLists.add(pbView);
            
            //[4]动态的添加进度条
            ll_pb_layout.addView(pbView);
            
        }
        
        
        //[5]开始移植 联网 获取文件长度
        new Thread(){public void run() {
            
            //[一 ☆☆☆☆]获取服务器文件的大小 要计算每个线程下载的开始位置和结束位置
            
            try {

                //(1) 创建一个url对象 参数就是网址
                URL url = new URL(path);
                //(2)获取HttpURLConnection 链接对象
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //(3)设置参数 发送get请求
                conn.setRequestMethod("GET"); //默认请求 就是get 要大写
                //(4)设置链接网络的超时时间
                conn.setConnectTimeout(5000);
                //(5)获取服务器返回的状态码
                int code = conn.getResponseCode(); //200 代表获取服务器资源全部成功 206请求部分资源
                if (code == 200) {

                    //(6)获取服务器文件的大小
                    int length = conn.getContentLength();
                    
                    //[6.1]把 线程的数量赋值给正在运行的线程
                    runningThread = threadCount;
                    
                    
                    System.out.println("length:"+length);
                    
                    //[二☆☆☆☆ ] 创建一个大小和服务器一模一样的文件 目的提前把空间申请出来
                    RandomAccessFile rafAccessFile = new RandomAccessFile(getFilename(path), "rw");
                    rafAccessFile.setLength(length);
                    
                    //(7)算出每个线程下载的大小
                    int blockSize = length /threadCount;
                    
                    //[三☆☆☆☆ 计算每个线程下载的开始位置和结束位置 ]
                    for (int i = 0; i < threadCount; i++) {
                        int startIndex = i * blockSize; //每个线程下载的开始位置
                        int endIndex = (i+1)*blockSize - 1;
                        //特殊情况 就是最后一个线程
                        if (i == threadCount - 1) {
                            //说明是最后一个线程
                            endIndex = length - 1;
                            
                        }
                        
                        System.out.println("线程id:::"+i + "理论下载的位置"+":"+startIndex+"-----"+endIndex);
                        
                        //四 开启线程去服务器下载文件
                        DownLoadThread downLoadThread = new DownLoadThread(startIndex, endIndex, i);
                        downLoadThread.start();
                        
                    }
                    
                    
                    
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            
            
        };}.start();
        
        
        
        
    }
    
    
    //定义线程去服务器下载文件
        private class DownLoadThread extends Thread{
            //通过构造方法把每个线程下载的开始位置和结束位置传递进来
            
            private int startIndex;
            private int endIndex;
            private int threadId;
            
            private int PbMaxSize; //代表当前线程下载的最大值
            //如果中断过 获取上次下载的位置
            private int pblastPostion;
            
            public DownLoadThread(int startIndex,int endIndex,int threadId){
                this.startIndex = startIndex;
                this.endIndex = endIndex;
                this.threadId = threadId;
            }
            
            @Override
            public void run() {
                //四 实现去服务器下载文件的逻辑
                
                try {

                    //(0)计算当前进度条的最大值
                    PbMaxSize = endIndex - startIndex;
                    //(1) 创建一个url对象 参数就是网址
                    URL url = new URL(path);
                    //(2)获取HttpURLConnection 链接对象
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    //(3)设置参数 发送get请求
                    conn.setRequestMethod("GET"); //默认请求 就是get 要大写
                    //(4)设置链接网络的超时时间
                    conn.setConnectTimeout(5000);
                    
                    
                    //[4.0]如果中间断过 继续上次的位置 继续下载 从文件中读取上次下载的位置
                    
                    File file =new File(getFilename(path)+threadId+".txt");
                    if (file.exists() && file.length()>0) {
                        FileInputStream fis = new FileInputStream(file);
                        BufferedReader bufr = new BufferedReader(new InputStreamReader(fis));
                        String lastPositionn = bufr.readLine(); //读取出来的内容就是上一次下载的位置
                        int lastPosition = Integer.parseInt(lastPositionn);

                        //[4.0]给我们定义的进度条条位置 赋值
                        pblastPostion = lastPosition - startIndex;
                        
                        //[4.0.1]要改变一下 startIndex 位置
                        startIndex = lastPosition + 1;
                        
                        
                        
                        System.out.println("线程id::"+threadId + "真实下载的位置"+":"+startIndex+"-----"+endIndex);
                        
                        fis.close(); //关闭流
                    }
                    
                    //[4.1]设置一个请求头Range (作用告诉服务器每个线程下载的开始位置和结束位置)
                    conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
                    
                    //(5)获取服务器返回的状态码
                    int code = conn.getResponseCode(); //200 代表获取服务器资源全部成功 206请求部分资源 成功
                    if (code == 206) {
                        //[6]创建随机读写文件对象
                        RandomAccessFile raf = new RandomAccessFile(getFilename(path), "rw");
                        //[6]每个线程要从自己的位置开始写
                        raf.seek(startIndex);
                        
                        InputStream in = conn.getInputStream(); //存的是feiq.exe
                        
                        //[7]把数据写到文件中
                        int len = -1;
                        byte[] buffer = new byte[1024*1024];//1Mb
                        
                        int total = 0; //代表当前线程下载的大小
                        
                        while((len = in.read(buffer))!=-1){
                            raf.write(buffer, 0, len);
                            
                            total +=len;
                            //[8]实现断点续传 就是把当前线程下载的位置 给存起来 下次再下载的时候 就是按照上次下载的位置继续下载 就可以了
                            int currentThreadPosition = startIndex + total; //比如就存到一个普通的.txt文本中
                            
                            //[9]用来存当前线程下载的位置
                            RandomAccessFile raff = new RandomAccessFile(getFilename(path)+threadId+".txt", "rwd");
                            raff.write(String.valueOf(currentThreadPosition).getBytes());
                            raff.close();
                            
                            //[10]设置一下当前进度条的最大值 和 当前进度
                            pbLists.get(threadId).setMax(PbMaxSize);//设置进度条的最大值
                            pbLists.get(threadId).setProgress(pblastPostion+total);//设置当前进度条的当前进度
                            
                            
                            
                        }
                        raf.close();//关闭流 释放资源
                        
                        System.out.println("线程id:"+threadId + "---下载完毕了");
                        
                        //[10]把.txt文件删除 每个线程具体什么时候下载完毕了 我们不知道
                        
                        synchronized (DownLoadThread.class) {
                            runningThread--;
                            if (runningThread == 0) {
                                //说明所有的线程都执行完毕了 就把.txt文件删除
                                for (int i = 0; i < threadCount; i++) {
                                    File delteFile = new File(getFilename(path)+i+".txt");
                                    delteFile.delete();
                                }
                                
                                
                                
                                
                            }
                        }
                        
                        
                        
                        
                        
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                
                
                
            }
        }
    
    
    
    //获取文件的名字 "http://192.168.11.73:8080/feiq.exe";
        public String getFilename(String path){
            
            int start = path.lastIndexOf("/")+1;
            String substring = path.substring(start);
            
            String fileName = Environment.getExternalStorageDirectory().getPath()+"/"+substring;
            return fileName;
        }
        

        
        
        
}
```

# 开源项目实现多线程断点下载

xUtils中的HttpUtils

实例:

```
//点击按钮实现断点续传下载逻辑
    public void click(View v){
        //[1]获取下载路径
        String path = et_path.getText().toString().trim();
        //[2]创建httputils对象
        HttpUtils http = new HttpUtils();
        //[3]实现断点下载 target下载文件的路径 autoResume 是否支持断点续传的逻辑
        http.download(path, "/mnt/sdcard/xpg.mp3", true, new RequestCallBack<File>() {
            
            //下载成功
            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
            
                Toast.makeText(getApplicationContext(), "下载成功", 1).show();
                
            }
            
            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                //total 代表总进度 current 代表当前进度
                
                pb.setMax((int) total);
                pb.setProgress((int) current);
            }
            
            //下载失败的回调
            @Override
            public void onFailure(HttpException error, String msg) {
                
            }
        });

        
    }
```
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值