最近看了看以前的代码,发现很多东西不看不写慢慢忘记了,所以想总结下,首先想到的就是android下的网络编程。慢慢总结,慢慢完善。
首先android常用的有三种网络通信方式,socket编程、HttpClient、HttpURLConnection。网络下编程必须添加权限:

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

socket编程

socket编程,最初接触java用socket写过简单的聊天小软件。socket翻译过来是‘插座’的意思,计算机专业术语则称之为‘套接字’,用于描述IP地址和端口(可以从socket的初始化语句理解),是一个通信链的句柄,可以用来实现不同虚拟机或不同计算机之间的通信。android中暂时没用到过,用到了再更新。

HttpClient

HttpClient是Apache对java中的HttpURLClient接口的封装,主要引用org.apache.http.**。Google在2.3版本之前推荐使用HttpClient,因为这个封装包安全性高,bug较少。

使用方法:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;



public class HttpClientUtils {
    private static HttpClient httpClient;
    private static HttpClientUtils instance = null;

    public static synchronized HttpClientUtils getInstance() {
        if (instance == null) {
            instance = new HttpClientUtils();
        }
        return instance;
    }

    private HttpClientUtils() {
        // 学习volley请求队列,HttpClient使用单例模式
        if (httpClient == null) {
            httpClient = new DefaultHttpClient();
        }
    }
    /**
     * 以get方式发送请求,访问接口
     * @param uri链接地址
     * @return 响应数据
     */
    private static String doHttpGet(String uri) {
        BufferedReader reader = null;
        StringBuffer sb = null;
        String result = "";
        HttpGet request = new HttpGet(uri);
        try {
            // 发送请求,得到响应
            HttpResponse response = httpClient.execute(request);
            // 请求成功,statuscode返回200
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                sb = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != reader) {
                    reader.close();
                    reader = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != sb) {
            result = sb.toString();
        }
        return result;
    }

    /**
     * 以post方式发送请求,访问接口
     * @param uri链接地址
     * @return 响应数据
     */
    private static String doHttpPost(String uri) {
        BufferedReader reader = null;
        StringBuffer sb = null;
        String result = "";
        HttpPost request = new HttpPost(uri);

        // 保存要传递的参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // 添加参数
        params.add(new BasicNameValuePair("parameter", "以Post方式发送请求"));

        try {
            // 设置字符集
            HttpEntity entity = new UrlEncodedFormEntity(params, "utf-8");
            // 请求对象
            request.setEntity(entity);
            // 发送请求
            HttpResponse response = httpClient.execute(request);
            // 请求成功
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("post success");
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                sb = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭流
                if (null != reader) {
                    reader.close();
                    reader = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != sb) {
            result = sb.toString();
        }
        return result;
    }

}

HttpURLConnection

HttpURLConnection在java.net下,继承自URLConnection类,相对于HttpClient具有扩展性高、灵活性高,更轻量级的优点,所以Google在2.3版本之后推荐大家使用HttpURLConnection来操作网络请求。

使用方法:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class HttpURLConnectUtils {

    private static HttpURLConnectUtils instance = null;

    public static synchronized HttpURLConnectUtils getInstance() {
        if (instance == null) {
            instance = new HttpURLConnectUtils();
        }
        return instance;
    }

    private HttpURLConnectUtils() {
    }

    // post
    public String dohttppost(String mUrl) throws IOException {

        URL url = new URL(mUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();//初始化创建HttpURLConnection实例
        httpURLConnection.setConnectTimeout(5000);//推荐设置网络延时
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
        httpURLConnection.setRequestMethod("POST");
        //设置参数
        OutputStream outputStream = httpURLConnection.getOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        String params = new String();//这里简单设置参数
        params = "name=" + URLEncoder.encode("高冉", "GBK");
        objectOutputStream.writeBytes(params);
        objectOutputStream.flush();
        objectOutputStream.close();
        //接收返回值
        //String msg = httpURLConnection.getResponseMessage();// 接收简单string
        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuilder builder = new StringBuilder();
        for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine()) {
            builder.append(s);
        }
        return builder.toString();
    }

    // get
    public String dohttpget(String mUrl) throws IOException {
        URL url = new URL(mUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(5000);//推荐设置网络延时
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.connect();

        // String msg = httpURLConnection.getResponseMessage();

        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuilder builder = new StringBuilder();
        for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine()) {
            builder.append(s);
        }

        return builder.toString();
    }
}

还需要注意一些细节:

1、post与get区别在于post将参数置于请求数据中,get则跟在url链接后面。
2、大文件下载操作要置于sd卡中,不要放在手机内存中操作,而且需要边读边写,不要使用Buffered做缓存。

到此android网络操作常用方法暂时总结完毕。