AKever

导航

Android(1)-HttpClient(apache)网络访问参考

本文是在android应用上使用apache的HttpClient访问网络-此处工具类代码并未实践,只做参考,具体使用,需要调试

HttpClient:apache家给android应用提供的的网络访问工具类

BasicHttpParams:Http访问参数类

HttpProtocolParams:Http访问参数协议类

ConnManagerParams:Http访问链接管理类

HttpConnectionParams:http访问链接参数类

SchemeRegistry:http访问策划注册类,SchemeRegistry类用来维持一组Scheme

ClientConnectionManager:http访问用户链接管理, ClientConnectionManager可用来设置访问线程安全,管理持久连接和同步访问持久连接来确保同一时间仅有一个线程可以访问一个连接

HttpPost:http访问Post请求类

HttpGet:http访问Get请求类

HttpResponse:http访问回应

HttpEntity:http访问数据实体,用来封装访问的数据,通过setEntity()传入httpPost或httpHost,同时会从HttpResponse放回该种数据实体;

      同时,官方提供了个中对HttpEntity的封装使用,如下:参考链接:http://my.oschina.net/u/1046089/blog?disp=2&p=1

  • BasicHttpEntity
  • ByteArrayEntity
  • StringEntity
  • InputStreamEntity
  • FileEntity
  • EntityTemplate
  • HttpEntityWrapper
  • BufferedHttpEntity

WARNING: 在http访问链接结束是记得释放链接 entity.consumeContent();

以下是源码类:

OwnHttpClient.java

package com.example.testhttpclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
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.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

public class OwnHttpClient {
    private static final int POOL_TIMEOUT = 20 * 1000;// 设置连接池超时20秒钟
    private static final int REQUEST_TIMEOUT = 5 * 1000;// 设置请求超时5秒钟
    private static final int REQUEST_WIFI_TIMEOUT = 10 * 1000;// 设置请求超时10秒钟
    private static final int SO_TIMEOUT = 5 * 1000; // 设置等待数据超时时间5秒钟
    
    private static OwnHttpClient instance;
    private DefaultHttpClient httpClient;    //DefaultHttpClient是实现HttpClient接口的子类
    private Context context;                //获取想取得该OwnHttpClient的的环境(Activity.this)
    private static String urlBasePath = "http://www.myhome.cn/oa";
    private String TAG = OwnHttpClient.class.getSimpleName();
    
    //构造函数中获取httpClient
    private OwnHttpClient(Context context) {
        this.context = context;
        this.httpClient = getHttpClient();
    }
    
    //Singleton
    public static OwnHttpClient getInstance(Context context) {
        if(instance == null) {
            synchronized (OwnHttpClient.class) {
                instance = new OwnHttpClient(context);
            }    
        }
        return instance;
    }
    
    //获取HttpClient
    public DefaultHttpClient getHttpClient() {
        if (null == httpClient) {
            // 设置一些基本参数
            BasicHttpParams httpParams = new BasicHttpParams();
            HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8);
            HttpProtocolParams.setUseExpectContinue(httpParams, true);
            HttpProtocolParams
                    .setUserAgent(
                            httpParams,
                            "Mozilla/5.0(Linux;U;Android 2.3.3;en-us;Nexus One Build.FRG83) "
                                    + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
            // 代理的设置
            HttpHost proxy = new HttpHost("10.60.8.20", 8080);
            httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); 
            
            /* 从连接池中取连接的超时时间 */
            ConnManagerParams.setTimeout(httpParams, POOL_TIMEOUT); // 设置连接池超时0秒钟
            if(NetManager.isWifiDataEnable((Activity)context)) {    //自定义类NetManager,判断是否为wifi请求,并 设置请求超时0秒钟
                HttpConnectionParams.setConnectionTimeout(httpParams,    
                        REQUEST_WIFI_TIMEOUT);    
            } else {
                HttpConnectionParams.setConnectionTimeout(httpParams,
                        REQUEST_TIMEOUT);  
            }
            HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT); // 设置等待数据超时时间0秒钟

            // 设置我们的HttpClient支持HTTP和HTTPS两种模式
            SchemeRegistry schReg = new SchemeRegistry();
            schReg.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));
            schReg.register(new Scheme("https", SSLSocketFactory
                    .getSocketFactory(), 443));
            
             // 使用线程安全的连接管理来创建HttpClient
            ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
                    httpParams, schReg);
            httpClient = new DefaultHttpClient(conMgr, httpParams);
            //httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));
        }
        return httpClient;
    }
    
    /**
     * make the connection of post
     * post request start-----------------------
     */
    //------normal post---------
    public String post(String url, NameValuePair... nameValuePairs) {
        return post(url, null, nameValuePairs);
    }
    public String post(String url, List<Header> headers, NameValuePair... nameValuePairs) {
        url = OwnHttpClient.urlBasePath + url;
        
        //参数(nameValuePairs)不为null,转换成list数组
        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        if(nameValuePairs != null) {                            
            for(NameValuePair param:nameValuePairs) {
                formParams.add(param);
            }
        }
        
        HttpPost httpPost = null;
        HttpResponse response = null;
        HttpEntity entity = null;   //BasicHttpEntity这类就是一个输入流的内容包装类,包装内容的相关的编码格式,长度等
        try {
            httpPost = getHttpPost(url, headers);        //获取HttpPost请求
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, HTTP.UTF_8));    //传入entity,设置参数传输
            response = httpClient.execute(httpPost);    //用HttpClient发送post请求
            entity = response.getEntity();                //获取post请求放回的数据
            
            StatusLine sl = response.getStatusLine();    //获取post他请求返回的状态行StatusLine
            if(sl.getStatusCode() == HttpStatus.SC_OK)    //获取状态行中的状态Code,并判断是否为SC_OK(200)
                return EntityUtils.toString(entity);    //为SC_OK这该post方法返回获取到的entity数据
        } catch(UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "UnsupportedEncodingException: " + e.getMessage());
        } catch(ClientProtocolException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "ClientProtocolException: " + e.getMessage());
        } catch(IOException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "IOException: " + e.getMessage());
        } finally {
            if(entity != null) {
                try {
                    entity.consumeContent();            // 释放连接(关闭流)
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    Log.e(TAG, "IOException: " + e.getMessage());
                }
            }
        }
        return "";
    }
    
    //--------post as stream-----------
    public String postAsStream(String url, String strEntity) {
        return postAsStream(url, null, strEntity);
    }
    public String postAsStream(String url, List<Header> headers, String strEntity) {
        url = OwnHttpClient.urlBasePath + url;
        
        HttpPost httpPost = null;
        HttpResponse response = null;
        HttpEntity entity = null;
        
        try {
            httpPost = getHttpPost(url, headers);                 //获取HttpPost请求
            StringEntity se = new StringEntity(strEntity);    
            
            //HttpEntityWrapper是创建包装实体的基类。,具体实现在实体类中操作,如ContentHttpEntity
            //BufferedHttpEntity是HttpEntityWrapper的子类
            //自定义封装HttpEntityWrapper
            ContentHttpEntity che = new ContentHttpEntity(se);        
            httpPost.setEntity(che);                            //传入entity,设置参数传输
            response = httpClient.execute(httpPost);            //用HttpClient发送post请求
            entity = response.getEntity();                        //获取post请求放回的数据
            
            StatusLine sl = response.getStatusLine();            //获取pos他请求返回的状态行StatusLine
            if(sl.getStatusCode() == HttpStatus.SC_OK)             //获取状态行中的状态Code,并判断是否为SC_OK(200)
                return EntityUtils.toString(entity);            //为SC_OK这该post方法返回获取到的entity数据
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "UnsupportedEncodingException: " + e.getMessage());
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "ClientProtocolException: " + e.getMessage());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "IOException: " + e.getMessage());
        } finally {
            if(entity != null) {
                try {
                    entity.consumeContent();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
    
    //get HttpPost
    private HttpPost getHttpPost(String url, List<Header> headers) {
        HttpPost httpPost = new HttpPost(url);
        if(headers != null) {
            for(Header header:headers) {
                httpPost.setHeader(header);
            }
        }
        return httpPost;
    }
    //--------post request end------------------------
    
    /**
     * make the connection of post
     * post request start
     */
//    public String get(String url) {
//        return get(url, null);
//    }
    public String get(String url, NameValuePair... nameValuePairs) {
        return get(url, null, nameValuePairs);
    }
    public String get(String url, List<Header> headers, NameValuePair... nameValuePairs) {
        url = OwnHttpClient.urlBasePath + url;
        
        StringBuffer sb = new StringBuffer();
        sb.append(url);
        if(nameValuePairs != null && nameValuePairs.length>0) {
            
            for(int i=0;i<nameValuePairs.length;i++) {
                if(i == 0) {
                    sb.append("?");
                } else if(i > 0) {
                    sb.append("&");
                }
                sb.append(String.format("%s=%s",
                        nameValuePairs[i].getName(),nameValuePairs[i].getValue()));
            }
        }
        //
        HttpGet httpGet = null;
        HttpResponse response = null;
        HttpEntity entity = null;     //BasicHttpEntity这类就是一个输入流的内容包装类,包装内容的相关的编码格式,长度等
        try {
            httpGet = getHttpGet(sb.toString(), headers);                //获取get请求
            response = httpClient.execute(httpGet);            //用HttpClient发送httpGet请求
            entity = response.getEntity();                    //获取response放回去的数据
            
            StatusLine sl = response.getStatusLine();        //获取response返回的状态行
            if(sl.getStatusCode() == HttpStatus.SC_OK)        //获取状态行中的状态码,并判断是否为SC_OK(200)
                return EntityUtils.toString(entity);        //如果请求正常,该方法返回entity中的数据
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "ClientProtocolException: " + e.getMessage());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "IOException: " + e.getMessage());
        } finally {
            if(entity != null) {                            //到最后不要忘了释放链接,关闭流
                try {
                    entity.consumeContent();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
    
    //get HttpGet
    private HttpGet getHttpGet(String url, List<Header> headers) {
        HttpGet httpGet = new HttpGet();
        if(headers != null) {
            for(Header header:headers) {
                httpGet.setHeader(header);
            }
        }
        return httpGet;
    }
    //----get request end---------------
    
    /*
     * cookie
     */
    public void clearCookie() {
        httpClient.getCookieStore().clear();    //清除cookie
    }
}

 

ContentHttpEntity.java

轻量封装HttpEntityWrapper,被OwnHttpClient.java调用

package com.example.testhttpclient;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;

public class ContentHttpEntity extends HttpEntityWrapper {

    public ContentHttpEntity(HttpEntity wrapped) {
        super(wrapped);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void writeTo(OutputStream outstream) throws IOException {
        // TODO Auto-generated method stub
        this.wrappedEntity.writeTo(outstream instanceof ContentOutStream ? outstream : new ContentOutStream(outstream));
    }

    static class ContentOutStream extends FilterOutputStream {
        public ContentOutStream(final OutputStream outstream) {
            super(outstream);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void write(byte[] buffer, int offset, int length)
                throws IOException {
            // TODO Auto-generated method stub
            super.write(buffer, offset, length);
        }

        @Override
        public void write(byte[] buffer) throws IOException {
            // TODO Auto-generated method stub
            super.write(buffer);
        }
    }
}

 

NetManager.java

自定网络管理类,此次用于判断是否使用wifi,被OwnHttpClient.java调用

package com.example.testhttpclient;

import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

public class NetManager {
    
    public static boolean isWifiDataEnable(Activity activity) {
        WifiManager wifiManager = 
                (WifiManager)activity.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
        if(wifiManager.isWifiEnabled() && ipAddress != 0) {
            return true;
        } else {
            return true;
        }
    }
}

 

本例子原型:https://github.com/eoecn/android-app/blob/master/source/src/cn/eoe/app/https/CustomHttpClient.java

学习参考:http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2112832.html

学习参考:http://my.oschina.net/u/1046089/blog?disp=2&p=1

 

posted on 2013-12-17 16:17  AKever  阅读(490)  评论(0)    收藏  举报