您的位置:首页 > 理论基础 > 计算机网络

Android网络连接汇总(代码篇)

2015-09-14 18:40 639 查看

程序(需要自己创建个服务器)

HttpClientActivity

package com.test.androidurlconnection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class HttpClientActivity extends Activity implements OnClickListener {
    private Button mButtonHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_httpclient);
        mButtonHttpClient = (Button) findViewById(R.id.button_httpclient);
        mButtonHttpClient.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button_httpclient:
            MyAsyncTask task = new MyAsyncTask();
            task.execute();
            break;

        default:
            break;
        }
    }

    class MyAsyncTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            String urlString = "http://192.168.0.198:8080/MyAndroidServlet/MyServlet?name=ngkang";
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(urlString);
            get.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
            try {
                HttpResponse response = client.execute(get);
                StatusLine statusLine = response.getStatusLine();
                int code = statusLine.getStatusCode();
                if (code == HttpURLConnection.HTTP_OK) {
                    HttpEntity entity = response.getEntity();
                    InputStream is = entity.getContent();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String line = br.readLine();
                    while (line != null) {
                        Log.d("", "" + line);
                        line = br.readLine();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "wancheng";
        }

    }
}


HttpVolley

package com.test.androidurlconnection;

import java.util.HashMap;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class HttpVolley extends Activity implements OnClickListener {
    private TextView mTextVolley;
    private Button mButtonVolley;
    private Button mButtonVolley_Post;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_volley);
        mButtonVolley = (Button) findViewById(R.id.button_volley);
        mButtonVolley.setOnClickListener(this);
        mTextVolley = (TextView) findViewById(R.id.textview_volley);
        mButtonVolley_Post = (Button) findViewById(R.id.button_volley_post);
        mButtonVolley_Post.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button_volley:
            RequestQueue mQueue = Volley.newRequestQueue(HttpVolley.this);
            StringRequest stringRequest = new StringRequest(Request.Method.GET, "http:360.com",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.d("TAG", response);
                            mTextVolley.setText(response);
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError arg0) {
                            Log.e("TAG", arg0.getMessage(), arg0);
                            mTextVolley.setText("网络错误");
                        }
                    });
            mQueue.add(stringRequest);

            break;
        case R.id.button_volley_post:
            // post方式提交数据
            RequestQueue mQueue2 = Volley.newRequestQueue(HttpVolley.this);
            StringRequest stringRequest2 = new StringRequest(Request.Method.POST,
                    "http://192.168.0.198:8080/MyAndroidServlet/MyServlet", new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.d("TAG", response);
                            mTextVolley.setText(response);
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError arg0) {
                            Log.e("TAG", arg0.getMessage(), arg0);
                            mTextVolley.setText("网络错误");
                        }
                    }) {
                // 此时创建了一个匿名内部类来提交数据
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("name", "kangkangkang");
                    return map;
                }
            };
            mQueue2.add(stringRequest2);
            break;

        default:
            break;
        }

    }

}


IndexActivity

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() {

        @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:
            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) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }).start();
            break;

        default:
            break;
        }
    }

    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;
                    publishProgress(sum, length);
                    index = input.read(array);
                }
                fos.flush();
                fos.close();
                input.close();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

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

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            int cont = (int) (values[0] * 100.0 / values[1]);
            mProgressBar.setProgress(cont);
        }

    }

}


MainActivity

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 Button mButtonHttpClient;
    private Button mButtonVolley;
    private Button mButtonXutils;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case FLAG:
                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);
        mButtonHttpClient = (Button) findViewById(R.id.button_httpclient);
        mButtonHttpClient.setOnClickListener(this);
        mButtonVolley = (Button) findViewById(R.id.button_volley_start);
        mButtonVolley.setOnClickListener(this);
        mButtonXutils = (Button) findViewById(R.id.button_xutils_start);
        mButtonXutils.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;
        case R.id.button_httpclient:
            Intent intent2 = new Intent(MainActivity.this, HttpClientActivity.class);
            startActivity(intent2);
        case R.id.button_volley_start:
            Intent intent3 = new Intent(MainActivity.this, HttpVolley.class);
            startActivity(intent3);
            break;
        case R.id.button_xutils_start:
            Intent intent4 = new Intent(MainActivity.this, XutilsActivity.class);
            startActivity(intent4);
            break;
        default:
            break;
        }
    }

    private void connectServlet() {
        String urlString = "http://192.168.0.198:8080/MyAndroidServlet/MyServlet";
        // 连接网络的权限不要忘记添加
        URL url;
        try {
            url = new URL(urlString);
            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();
            }
            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();
        }
    }

}


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;
    private String urlPath;
    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();
        }
    }
}


XutilsActivity

package com.test.androidurlconnection;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import android.app.Activity;
import android.os.Bundle;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class XutilsActivity extends Activity implements OnClickListener{
    @ViewInject(R.id.button_httputils)
    private Button mButtonHttputils;
    @ViewInject(R.id.button_httputils_post)
    private Button mButtonHttputilsPost;
    private TextView mTextViewutils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xutils);
        ViewUtils.inject(this);

        mTextViewutils=(TextView) findViewById(R.id.utils_textview);
        mButtonHttputilsPost=(Button) findViewById(R.id.button_httputils_post);
        mButtonHttputilsPost.setOnClickListener(this);

    }
    @OnClick(R.id.button_httputils)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button_httputils:
            HttpUtils utils=new HttpUtils();
            //应该用httpClient.HttpMethod.GET,此处因为没有找到包,所以很尴尬。
            utils.send(HttpMethod.GET, "http://www.360.com", new RequestCallBack<String>() {

                @Override
                public void onFailure(HttpException arg0, String arg1) {

                }

                @Override
                public void onSuccess(ResponseInfo<String> arg0) {
                    mTextViewutils.setText(arg0.result);

                }
            });
            break;
        case R.id.button_httputils_post:
            HttpUtils utilspost=new HttpUtils();
            RequestParams params=new RequestParams();
            params.addBodyParameter("name", "xiaohong");
            utilspost.send(HttpMethod.POST, "http://192.168.0.198:8080/MyAndroidServlet/MyServlet",params,new RequestCallBack<String>() {

                @Override
                public void onFailure(HttpException arg0, String arg1) {                    
                }
                @Override
                public void onSuccess(ResponseInfo<String> arg0) {
                    mTextViewutils.setText(arg0.result);

                }
            });
            break;

        default:
            break;
        }
    }

}


布局

activity_httpclient.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button 
        android:id="@+id/button_httpclient"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HttpClient"/>

</LinearLayout>


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"
            style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/button_morelinedownload"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="多线程下载" />
    </LinearLayout>

</ScrollView>


activity_main.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"
            style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/button_morelinedownload"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="多线程下载" />
    </LinearLayout>

</ScrollView>


activity_volley.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button_volley"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="VolleyGet" />

    <Button
        android:id="@+id/button_volley_post"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="VolleyPost" />

    <TextView
        android:id="@+id/textview_volley"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

</LinearLayout>


activity_xutils.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button_httputils"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HttpUtils" />

    <Button
        android:id="@+id/button_httputils_post"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HttpUtilsPost" />

    <TextView
        android:id="@+id/utils_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

</LinearLayout>


配置篇

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.androidurlconnection"
    android:versionCode="1"
    android:versionName="1.0" >

    <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" />

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".IndexActivity" >
        </activity>
        <activity android:name=".HttpClientActivity" >
        </activity>
        <activity android:name=".HttpVolley" >
        </activity>
        <activity android:name=".XutilsActivity" >
        </activity>
    </application>

</manifest>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: