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

客户端开发--3控制器开发准备(2)【网络通信模块】

2015-07-28 08:51 573 查看
网络通信是联网应用的核心基础模块。Android应用网络通信可以通过3种方式实现:

java.net.*提供的标准java接口

android.net.*提供的Android接口

org.apache.http.*提供的接口(apache组织提供)

一、使用HttpClient进行网络通信

出于安全性和稳定性考虑,采用Apache提供的HttpClient进行网络通信。本应用中,对HttpClient进行整理包装形成新类AppClient,该类位于com.app.demos.util中。

package com.app.demos.uti;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.app.demos.base.C;

import android.util.Log;

/**
 * 网络连接<br>
 * 对原生HttpClient的进一步封装
 * @author Administrator
 *
 */
@SuppressWarnings("rawtypes")
public class AppClient {

    // 压缩配置
    final private static int CS_NONE = 0;
    final private static int CS_GZIP = 1;

    // 必要类属性
    private String apiUrl;
    private HttpParams httpParams;
    private HttpClient httpClient;
    private int timeoutConnection = 10000;
    private int timeoutSocket = 10000;
    private int compress = CS_NONE;

    // 默认字符集为UTF-8
    private String charset = HTTP.UTF_8;

    public AppClient (String url) {
        initClient(url);
    }

    public AppClient (String url, String charset, int compress) {
        initClient(url);
        this.charset = charset;  
        this.compress = compress; 
    }

    private void initClient (String url) {
        // 初始化API的URL地址,自动添加Seession ID
        this.apiUrl = C.api.base + url;
        String apiSid = AppUtil.getSessionId();
        if (apiSid != null && apiSid.length() > 0) {
            this.apiUrl += "?sid=" + apiSid;
        }
        httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
        httpClient = new DefaultHttpClient(httpParams);
    }

    /**
     * 设置用户上网方式
     */
    public void useWap () {
        HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    /**
     * 处理HTTP的GET请求
     * @return
     * @throws Exception
     */
    public String get () throws Exception {
        try {
            HttpGet httpGet = headerFilter(new HttpGet(this.apiUrl));
            Log.w("AppClient.get.url", this.apiUrl);
            // 发送get请求
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String httpResult = resultFilter(httpResponse.getEntity());
                Log.w("AppClient.get.result", httpResult);
                return httpResult;
            } else {
                return null;
            }
        } catch (ConnectTimeoutException e) {
            throw new Exception(C.err.network);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 处理HTTP的POST请求
     * @param urlParams
     * @return
     * @throws Exception
     */
    public String post (HashMap urlParams) throws Exception {
        try {
            HttpPost httpPost = headerFilter(new HttpPost(this.apiUrl));
            List<NameValuePair> postParams = new ArrayList<NameValuePair>();
            // 构造POST请求参数
            Iterator it = urlParams.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                postParams.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
            }
            if (this.charset != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(postParams, this.charset));
            } else {
                httpPost.setEntity(new UrlEncodedFormEntity(postParams));
            }
            Log.w("AppClient.post.url", this.apiUrl);
            Log.w("AppClient.post.data", postParams.toString());
            // 发送POST请求
            HttpResponse httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String httpResult = resultFilter(httpResponse.getEntity());
                Log.w("AppClient.post.result", httpResult);
                return httpResult;
            } else {
                return null;
            }
        } catch (ConnectTimeoutException e) {
            throw new Exception(C.err.network);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 设置HTTP请求头,是否使用GZIP
     * @param httpGet
     * @return
     */
    private HttpGet headerFilter (HttpGet httpGet) {
        // 为GET请求设置请求头
        switch (this.compress) {
            case CS_GZIP:
                httpGet.addHeader("Accept-Encoding", "gzip");
                break;
            default :
                break;
        }
        return httpGet;
    }
    /**
     * 设置HTTP请求头,是否使用GZIP
     * @param httpPost
     * @return
     */
    private HttpPost headerFilter (HttpPost httpPost) {
        // 为Post请求设置请求头
        switch (this.compress) {
            case CS_GZIP:
                httpPost.addHeader("Accept-Encoding", "gzip");
                break;
            default :
                break;
        }
        return httpPost;
    }
    /**
     * 对请求结果进行GIZP解码
     * @param entity
     * @return
     */
    private String resultFilter(HttpEntity entity){
        String result = null;
        try {
            // 对请求结果进行GIZP解码
            switch (this.compress) {
                case CS_GZIP:
                    result = AppUtil.gzipToString(entity);
                    break;
                default :
                    result = EntityUtils.toString(entity);
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}


说明:该类中主要方法是get()|post(),可以通过该方法从网络获取数据。该类主要用在两个地方:一是异步任务中网络请求逻辑;二是即时通知服务中的网络请求逻辑。

二、支持CMWAP网络接入方式

在4.0之后,不需要对联网方式进行判断,此处就不做记录。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: