Android连接服务器,从服务器获取数据,以及从服务器下载文件(单,多线程)

首先需要在Eclipse中创建一个服务器,在其中存入要下载的文件,具体可参考之前的服务器篇。

ScollView可以上下滑动

另外还有,android中的网络连接与之前java中可以通用,可以参照之前服务器客户端通信篇。

添加的权限

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

程序

Android主程序

    package com.test.androidurlconnection;

import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
    private final static int FLAG=123;
    private Button mButtonConnection;
    private Button mButtonStartInterface;
    private TextView mTextView;
    private Handler handler=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case FLAG:
                //此处用handler是为了更新UI中的TextView
                String content=(String) msg.obj;
                Log.d("w123e", content);
                mTextView.setText(content);
                break;
            default:
                break;
            }
            super.handleMessage(msg);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView=(TextView) findViewById(R.id.text_view);
        mButtonConnection = (Button) findViewById(R.id.button_connection);
        mButtonConnection.setOnClickListener(this);
        mButtonStartInterface=(Button) findViewById(R.id.button_start_download);
        mButtonStartInterface.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button_connection:
            //直接开启一个线程进行连网操作
            new Thread(new Runnable() {
                @Override
                public void run() {
                    connectServlet();
                }
            }).start();
            break;
        case R.id.button_start_download:
            //启动第二个界面
            Intent intent=new Intent(MainActivity.this,IndexActivity.class);
            startActivity(intent);
            break;
        default:
            break;
        }
    }

    private void connectServlet() {
        String urlString = "http://192.168.0.198:8080/MyAndroidServlet/MyServlet";
        //连接网络的权限不要忘记添加
        URL url;
        try {
            //创建URL,传入网址
            url = new URL(urlString);
            //建立URL连接,打开连接
            URLConnection connect = url.openConnection();
            //获得连接的输入流,读取传过来的信息
            InputStream input=connect.getInputStream();
            //封装读取文件
            BufferedReader br=new BufferedReader(new InputStreamReader(input));
            String line =br.readLine();
            StringBuffer builder=new StringBuffer();
            while(line!=null){
                builder.append(line);
                Log.d("qwe", line);
                line=br.readLine();
            }
            //通过Msg来传递消息,在handler中更新线程
            Message msg=handler.obtainMessage();
            msg.what=FLAG;
            msg.obj=builder.toString().trim();
            Log.d("dfdsfsdfe", builder.toString().trim());
            handler.sendMessage(msg);
            br.close();
            input.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

IndexActivity程序(两个用的是同一个ProgressBar)

package com.test.androidurlconnection;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class IndexActivity extends Activity implements OnClickListener {
    private final static int MULTI_LINE = 1234;
    private Button mButtonLoad;
    private Button mHttpDoGet;
    private Button mHttpDoPost;
    private Button mMoreLine;
    private ProgressBar mProgressBar;
    private int length;
    private Handler handle = new Handler() {
        /**
         *多线程下载时使用handler来更新porgressbar
         */
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MULTI_LINE:
                int progress = msg.arg1;
                mProgressBar.setProgress(msg.arg1 * 100 / length);
                break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        mHttpDoGet = (Button) findViewById(R.id.button_httpdoget);
        mHttpDoGet.setOnClickListener(this);
        mHttpDoPost = (Button) findViewById(R.id.button_httpdopost);
        mHttpDoPost.setOnClickListener(this);
        mMoreLine = (Button) findViewById(R.id.button_morelinedownload);
        mMoreLine.setOnClickListener(this);
        mButtonLoad = (Button) findViewById(R.id.button_download);
        mButtonLoad.setOnClickListener(this);
        mProgressBar = (ProgressBar) findViewById(R.id.progressbar);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button_httpdoget:

            break;
        case R.id.button_httpdopost:

            break;
        case R.id.button_download:
            //单线程下载,使用AsyncTask,启动时用exectue()
            MyAsyncTast task = new MyAsyncTast();
            task.execute();
            break;
        case R.id.button_morelinedownload:
            //在一个线程中开启多个线程进行下载
            new Thread(new Runnable() {

                @Override
                public void run() {
                    String urlString = "http://192.168.0.198:8080/MyAndroidServlet/qwe.mp3";
                    // 连接网络的权限不要忘记添加
                    URL url;
                    try {
                        url = new URL(urlString);
                        URLConnection connect = url.openConnection();
                        //获得传输内容的长度
                        length = connect.getContentLength();
                        InputStream input = connect.getInputStream();
                        //定义要写入文件的路径
                        File file = new File(Environment.getExternalStorageDirectory(), "asdfghj.mp3");
                        //当文件不存在时创建文件
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                        MyThread[] threads = new MyThread[5];
                        for (int i = 0; i < 5; i++) {
                            //开启自定义的线程,并传入相应的值
                            MyThread thread = null;
                            if (i == 4) {
                                //最后一个文件传输的内容可能不为整数,所以要单独拿出来进行传输
                                thread = new MyThread(length / 5 * 4, length, urlString, file.getAbsolutePath());
                            } else {
                                //注意减一
                                thread = new MyThread(length / 5 * i, length / 5 * (i + 1)-1, urlString,
                                        file.getAbsolutePath());
                            }
                            //开启线程
                            thread.start();
                            threads[i] = thread;
                        }

                        //但没有下载完时,不断对已经下载的数量进行更新。
                        boolean isFinish = true;
                        while (isFinish) {
                            int sum = 0;
                            for (MyThread thread : threads) {
                                sum += thread.getSum();
                            }
                            Message msg = handle.obtainMessage();
                            msg.what = MULTI_LINE;
                            msg.arg1 = sum;
                            handle.sendMessage(msg);
                            if (sum + 10 >= length) {
                                isFinish = false;
                            }
                            //下载完时,线程休眠
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {

                                e.printStackTrace();
                            }
                        }
                    } catch (MalformedURLException e) {                     
                        e.printStackTrace();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            break;

        default:
            break;
        }
    }
    //单线程下载时使用的AsyncTask线程
    class MyAsyncTast extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... params) {
            String urlString = "http://192.168.0.198:8080/MyAndroidServlet/qwe.mp3";
            // 连接网络的权限不要忘记添加
            URL url;
            try {
                url = new URL(urlString);
                URLConnection connect = url.openConnection();
                int length = connect.getContentLength();
                InputStream input = connect.getInputStream();
                File file = new File(Environment.getExternalStorageDirectory(), "keng1.mp3");
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(file);
                //读取文件
                byte array[] = new byte[1024];
                int sum = 0;
                int index = input.read(array);
                while (index != -1) {
                    fos.write(array, 0, index);
                    sum += index;
                    //传入给前台值,以便对Progressbar进行操作
                    publishProgress(sum, length);
                    index = input.read(array);
                }
                fos.flush();
                fos.close();
                input.close();
            } catch (MalformedURLException e) {             
                e.printStackTrace();
            }
            catch (IOException e) {         
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            //在前台设置ProgressBar的值
            super.onProgressUpdate(values);
            int cont = (int) (values[0] * 100.0 / values[1]);
            mProgressBar.setProgress(cont);
        }

    }

}

MyThread多线程下载的线程

package com.test.androidurlconnection;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.os.Environment;

public class MyThread extends Thread{
    private int sum;
    public int getSum() {
        return sum;
    }
    //传入线程开始的地方
    private long start;
    //传入单个线程结束的地方
    private long end;
    //传入要下载的url路径
    private String urlPath;
    //传入要保存的file路径
    private String filePath;
    public MyThread() {
    }
    public MyThread(long start, long end, String urlPath, String filePath) {
        this.start = start;
        this.end = end;
        this.urlPath = urlPath;
        this.filePath = filePath;
    }

    @Override
    public void run() {
        try {
            URL url = new URL(urlPath);
            URLConnection connect = url.openConnection();
            //此条语句用时可搜索起作用
            connect.setAllowUserInteraction(true);
            //设置请求的的格式
            connect.setRequestProperty("Range", "bytes="+start+"-"+end);
            //得到服务器传过来的输入流
            InputStream input=connect.getInputStream();
            byte array[]=new byte[1024];
            File file=new File(filePath);
            //用随机读取文件,因为可以调整读取的位置
            RandomAccessFile randomAccessFile=new RandomAccessFile(file, "rw");
            //调整读取位置
            randomAccessFile.seek(start);
            int index=input.read(array);
            while(index!=-1){
                //对文件进行写的操作
                randomAccessFile.write(array, 0, index);
                sum+=index;
                index=input.read(array);
            }
            randomAccessFile.close();
            input.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

布局文件

主布局

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >
    <LinearLayout
        android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <Button
        android:id="@+id/button_connection"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button 
        android:id="@+id/button_start_download"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="启动下载界面"/>
    <TextView 
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    </LinearLayout>
</ScrollView>

activity_index.xml布局文件

    <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <Button 
            android:id="@+id/button_httpdoget"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="DoGet"
            />
        <Button 
            android:id="@+id/button_httpdopost"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="DoPost"
            />
        <Button 
            android:id="@+id/button_download"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="下载"
            />
        <ProgressBar
            android:id="@+id/progressbar" 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"/>
        <Button 
            android:id="@+id/button_morelinedownload"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="多线程下载"
            />
    </LinearLayout>
</ScrollView>

运行图

这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值