android的网络访问

1、核心类NetWorkCore,处理发送请求

  1. import java.io.IOException;  
  2. import java.io.InputStream;  
  3.   
  4. import org.apache.http.HttpEntity;  
  5. import org.apache.http.HttpHost;  
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.HttpStatus;  
  8. import org.apache.http.client.ClientProtocolException;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.methods.HttpGet;  
  11. import org.apache.http.client.methods.HttpPost;  
  12. import org.apache.http.conn.params.ConnRouteParams;  
  13. import org.apache.http.entity.ByteArrayEntity;  
  14. import org.apache.http.entity.StringEntity;  
  15. import org.apache.http.impl.client.DefaultHttpClient;  
  16. import org.apache.http.params.BasicHttpParams;  
  17. import org.apache.http.params.HttpConnectionParams;  
  18. import org.apache.http.params.HttpParams;  
  19.   
  20. /** 
  21.  * 网络请求核心类,用于处理发送请求和返回,单例 
  22.  *  
  23.  * @author Administrator 
  24.  *  
  25.  */  
  26. public class NetworkCore {  
  27.     //连接超时(ms)  
  28.     private static final int timeoutConnection = 30000;  
  29.     //响应超时(ms)  
  30.     private static final int timeoutSocket = 50000;  
  31.   
  32.     private static NetworkCore instance;  
  33.     /*get请求*/  
  34.     private HttpGet httpGet;  
  35.     /*post请求*/  
  36.     private HttpPost httpPost;  
  37.       
  38.     public static NetworkCore Instance() {  
  39.         if (instance == null) {  
  40.             instance = new NetworkCore();  
  41.         }  
  42.         return instance;  
  43.     }  
  44.     /** 
  45.      * 发送请求 
  46.      * @param request 请求线程对象 
  47.      * @return 请求结果 
  48.      */  
  49.     public NetWorkResponseMsg perform(DoRequestRunnable request) {  
  50.         NetWorkResponseMsg msg = null;  
  51.         NetworkRequestMsg mNetworkRequestMsg = request.getmNetworkRequestMsg();  
  52.         try {  
  53.             if (NetworkRequestMsg.POST.equals(mNetworkRequestMsg.getType())) {  
  54.                 msg = handlePostRequest(mNetworkRequestMsg);  
  55.             } else {  
  56.                 msg = handleGetRequest(mNetworkRequestMsg);  
  57.             }  
  58.             if (msg.getInputStream()==null) {  
  59.                 msg.setResponseMsg(NetworkError.NODATA);  
  60.             }  
  61.             request.handleNetResponseMsg(msg);  
  62.         } catch (IOException e) {  
  63.             msg.setResponseMsg(NetworkError.CONNECT_ERROR);  
  64.         } finally {  
  65.             msg.closeStream();  
  66.         }  
  67.         return msg;  
  68.     }  
  69.     /** 
  70.      * get请求 
  71.      * @param mNetworkRequestMsg 
  72.      * @return 
  73.      * @throws ClientProtocolException 
  74.      * @throws IOException 
  75.      */  
  76.     private NetWorkResponseMsg handleGetRequest(NetworkRequestMsg mNetworkRequestMsg)  
  77.             throws ClientProtocolException, IOException {  
  78.         InputStream is = null;  
  79.         StringBuffer finalURL = new StringBuffer(mNetworkRequestMsg.getUrl());  
  80.         int index = finalURL.indexOf("?");  
  81.         if (null != mNetworkRequestMsg.getParam()) {  
  82.             for (String paramName : mNetworkRequestMsg.getParam()  
  83.                     .getParamNames()) {  
  84.                 if (index == -1) {  
  85.                     finalURL.append("?"  
  86.                             + paramName  
  87.                             + "="  
  88.                             + mNetworkRequestMsg.getParam().getParamValue(  
  89.                                     paramName));  
  90.                 } else {  
  91.                     finalURL.append("&"  
  92.                             + paramName  
  93.                             + "="  
  94.                             + mNetworkRequestMsg.getParam().getParamValue(  
  95.                                     paramName));  
  96.                 }  
  97.                 index++;  
  98.             }  
  99.             mNetworkRequestMsg.setUrl(finalURL.toString());  
  100.         }  
  101.         httpGet = new HttpGet(finalURL.toString());  
  102.         if (mNetworkRequestMsg.getParam().getParamNames().size() > 0) {  
  103.             for (String headerName : mNetworkRequestMsg.getParam()  
  104.                     .getHeaderNames()) {  
  105.                 httpGet.addHeader(headerName, mNetworkRequestMsg.getParam()  
  106.                         .getHeaderValue(headerName));  
  107.             }  
  108.         }  
  109.         mNetworkRequestMsg.getParam().clearCache();  
  110.         HttpParams httpParameters = new BasicHttpParams();  
  111.         HttpConnectionParams.setConnectionTimeout(httpParameters,  
  112.                 timeoutConnection);  
  113.         HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);  
  114.   
  115.         HttpClient httpclient = new DefaultHttpClient(httpParameters);  
  116.         if (mNetworkRequestMsg.isNeedProxy()) {  
  117.             String address = mNetworkRequestMsg.getProxyAddress() == null ? NetworkConfig.DEFAULT_PROXY  
  118.                     : mNetworkRequestMsg.getProxyAddress();  
  119.             int port = mNetworkRequestMsg.getProxyPort() == 0 ? NetworkConfig.DEFAULT_PROXYPORT  
  120.                     : mNetworkRequestMsg.getProxyPort();  
  121.             setProxy(httpclient, address, port);  
  122.         }  
  123.         HttpResponse httpResponse = httpclient.execute(httpGet);  
  124.         if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
  125.             is = httpResponse.getEntity().getContent();  
  126.         }   
  127.         return new NetWorkResponseMsg(is,httpResponse.getStatusLine().getStatusCode());  
  128.     }  
  129.     /** 
  130.      * post请求 
  131.      * @param mNetworkRequestMsg 
  132.      * @return 
  133.      * @throws ClientProtocolException 
  134.      * @throws IOException 
  135.      */  
  136.     private NetWorkResponseMsg handlePostRequest(NetworkRequestMsg mNetworkRequestMsg)  
  137.             throws ClientProtocolException, IOException {  
  138.         InputStream is = null;  
  139.         HttpEntity httpentity = null;  
  140.         StringBuffer finalURL = new StringBuffer(mNetworkRequestMsg.getUrl());  
  141.         int index = finalURL.indexOf("?");  
  142.         if (null != mNetworkRequestMsg.getParam()) {  
  143.             for (String paramName : mNetworkRequestMsg.getParam()  
  144.                     .getParamNames()) {  
  145.                 if (index == -1) {  
  146.                     finalURL.append("?"  
  147.                             + paramName  
  148.                             + "="  
  149.                             + mNetworkRequestMsg.getParam().getParamValue(  
  150.                                     paramName));  
  151.                 } else {  
  152.                     finalURL.append("&"  
  153.                             + paramName  
  154.                             + "="  
  155.                             + mNetworkRequestMsg.getParam().getParamValue(  
  156.                                     paramName));  
  157.                 }  
  158.                 index++;  
  159.             }  
  160.             mNetworkRequestMsg.setUrl(finalURL.toString());  
  161.         }  
  162.         httpPost = new HttpPost(finalURL.toString());  
  163.         if (mNetworkRequestMsg.getParam().getParamNames().size() > 0) {  
  164.             for (String headerName : mNetworkRequestMsg.getParam()  
  165.                     .getHeaderNames()) {  
  166.                 httpPost.addHeader(headerName, mNetworkRequestMsg.getParam()  
  167.                         .getHeaderValue(headerName));  
  168.             }  
  169.         }  
  170.         mNetworkRequestMsg.getParam().clearCache();  
  171.         if (mNetworkRequestMsg.getParam().getArrayBody() != null) {  
  172.             httpentity = new ByteArrayEntity(mNetworkRequestMsg.getParam()  
  173.                     .getArrayBody());  
  174.         } else if (mNetworkRequestMsg.getParam().getBody() != null) {  
  175.             httpentity = new StringEntity(mNetworkRequestMsg.getParam()  
  176.                     .getBody());  
  177.         }  
  178.         if (null != httpentity) {  
  179.             httpPost.setEntity(httpentity);  
  180.         }  
  181.         HttpParams httpParameters = new BasicHttpParams();  
  182.         HttpConnectionParams.setConnectionTimeout(httpParameters,  
  183.                 timeoutConnection);  
  184.         HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);  
  185.         HttpClient httpclient = new DefaultHttpClient(httpParameters);  
  186.         if (mNetworkRequestMsg.isNeedProxy()) {  
  187.             String address = mNetworkRequestMsg.getProxyAddress() == null ? NetworkConfig.DEFAULT_PROXY  
  188.                     : mNetworkRequestMsg.getProxyAddress();  
  189.             int port = mNetworkRequestMsg.getProxyPort() == 0 ? NetworkConfig.DEFAULT_PROXYPORT  
  190.                     : mNetworkRequestMsg.getProxyPort();  
  191.             setProxy(httpclient, address, port);  
  192.         }  
  193.         HttpResponse httpResponse = httpclient.execute(httpPost);  
  194.         if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
  195.             is = httpResponse.getEntity().getContent();  
  196.         }  
  197.         return new NetWorkResponseMsg(is,httpResponse.getStatusLine().getStatusCode());  
  198.     }  
  199.     /** 
  200.      * 断开连接 
  201.      */  
  202.     public void abort(){  
  203.         if(httpGet != null){  
  204.             if(!httpGet.isAborted()){  
  205.                 httpGet.abort();  
  206.             }  
  207.         }  
  208.         if(httpPost != null){  
  209.             if(!httpPost.isAborted()){  
  210.                 httpPost.abort();  
  211.             }  
  212.         }  
  213.     }  
  214.     /** 
  215.      *  
  216.      * @param httpclient 
  217.      * @param address 
  218.      * @param port 
  219.      */  
  220.     private void setProxy(HttpClient httpclient, String address, int port) {  
  221.         HttpHost proxy = new HttpHost(address, port);  
  222.         httpclient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,  
  223.                 proxy);  
  224.     }  
  225.   
  226. }  

2、请求封装类NetworkRequestMsg:
  1. public class NetworkRequestMsg extends Message {  
  2.       
  3.     public static final String GET = "GET";  
  4.     public static final String POST = "POST";  
  5.       
  6.   
  7.     /** 
  8.      * 产生自增ID计数器 
  9.      */  
  10.     private static short ID = 0;  
  11.   
  12.     /** 
  13.      * 当前消息id 
  14.      */  
  15.     private short id = 0;  
  16.   
  17.     /** 
  18.      * 当前请求类型(GET/POST) 
  19.      */  
  20.     private String type;  
  21.   
  22.     /** 
  23.      * 请求地址URL 
  24.      */  
  25.     private String url;  
  26.   
  27.     /** 
  28.      * 请求消息参数 
  29.      */  
  30.     private Parameter param;  
  31.   
  32.     /** 
  33.      * 数据连接返回值 
  34.      */  
  35.     private byte retcode = -1;  
  36.   
  37.     /** 
  38.      * 请求是否取消 
  39.      */  
  40.     private boolean cancel = false;  
  41.   
  42.     /** 
  43.      * 是否正在发送数据 
  44.      */  
  45.     private boolean sending = false;  
  46.   
  47.     /** 
  48.      * 是否是下载类型 
  49.      */  
  50.     private boolean download = false;  
  51.   
  52.     /** 
  53.      * 重发次数 
  54.      */  
  55.     private byte sendTime = 0;  
  56.       
  57.     /** 
  58.      * 网络数据解析协议 
  59.      */  
  60.     private String protocol;  
  61.       
  62.     /** 
  63.      * 是否需要代理 
  64.      */  
  65.     private boolean isNeedProxy;  
  66.       
  67.     /** 
  68.      * 代理地址 
  69.      */  
  70.     private String proxyAddress;  
  71.       
  72.       
  73.     /** 
  74.      * 代理端口 
  75.      */  
  76.     private int proxyPort;   
  77.   
  78.       
  79.       
  80.   
  81.     public NetworkRequestMsg(String _url,String _type ,Parameter _param,boolean isNeedProxy,String _proxyAddress,int _proxyPort){  
  82.           
  83.         this.url = _url;  
  84.         this.type = _type;  
  85.         this.isNeedProxy = isNeedProxy;  
  86.         this.param = _param;  
  87.         this.proxyAddress = _proxyAddress;  
  88.         this.proxyPort = _proxyPort;  
  89.           
  90.     }  
  91.       
  92.   
  93.     public static short getID() {  
  94.         return ID;  
  95.     }  
  96.   
  97.     public static void setID(short iD) {  
  98.         ID = iD;  
  99.     }  
  100.   
  101.     public short getId() {  
  102.         return id;  
  103.     }  
  104.   
  105.     public void setId(short id) {  
  106.         this.id = id;  
  107.     }  
  108.   
  109.     public String getType() {  
  110.         return type;  
  111.     }  
  112.   
  113.     public void setType(String type) {  
  114.         this.type = type;  
  115.     }  
  116.   
  117.     public String getUrl() {  
  118.         return url;  
  119.     }  
  120.   
  121.     public void setUrl(String url) {  
  122.         this.url = url;  
  123.     }  
  124.   
  125.     public byte getRetcode() {  
  126.         return retcode;  
  127.     }  
  128.   
  129.     public void setRetcode(byte retcode) {  
  130.         this.retcode = retcode;  
  131.     }  
  132.   
  133.     public boolean isCancel() {  
  134.         return cancel;  
  135.     }  
  136.   
  137.     public void setCancel(boolean cancel) {  
  138.         this.cancel = cancel;  
  139.     }  
  140.   
  141.     public boolean isSending() {  
  142.         return sending;  
  143.     }  
  144.   
  145.     public void setSending(boolean sending) {  
  146.         this.sending = sending;  
  147.     }  
  148.   
  149.     public boolean isDownload() {  
  150.         return download;  
  151.     }  
  152.   
  153.     public void setDownload(boolean download) {  
  154.         this.download = download;  
  155.     }  
  156.   
  157.     public byte getSendTime() {  
  158.         return sendTime;  
  159.     }  
  160.   
  161.     public void setSendTime(byte sendTime) {  
  162.         this.sendTime = sendTime;  
  163.     }  
  164.     public Parameter getParam() {  
  165.         return param;  
  166.     }  
  167.   
  168.   
  169.     public void setParam(Parameter param) {  
  170.         this.param = param;  
  171.     }  
  172.   
  173.   
  174.       
  175.       
  176.       
  177.       
  178.     public String getProtocol() {  
  179.         return protocol;  
  180.     }  
  181.   
  182.   
  183.     public void setProtocol(String protocol) {  
  184.         this.protocol = protocol;  
  185.     }  
  186.   
  187.   
  188.     public boolean isNeedProxy() {  
  189.         return isNeedProxy;  
  190.     }  
  191.   
  192.   
  193.     public void setNeedProxy(boolean isNeedProxy) {  
  194.         this.isNeedProxy = isNeedProxy;  
  195.     }  
  196.       
  197.     public String getProxyAddress() {  
  198.         return proxyAddress;  
  199.     }  
  200.   
  201.     public void setProxyAddress(String proxyAddress) {  
  202.         this.proxyAddress = proxyAddress;  
  203.     }  
  204.   
  205.     public int getProxyPort() {  
  206.         return proxyPort;  
  207.     }  
  208.   
  209.     public void setProxyPort(int proxyPort) {  
  210.         this.proxyPort = proxyPort;  
  211.     }  
  212. }  

请求参数封装类Parameter:
  1. import java.util.ArrayList;  
  2. import java.util.HashMap;  
  3.   
  4. public class Parameter {  
  5.       
  6.     private HashMap<String,String> header = new HashMap<String,String>();  
  7.     private ArrayList<String> allHeaderNames = new ArrayList<String>();  
  8.     //参数信息  
  9.     private HashMap<String,String> param = new HashMap<String,String>();  
  10.     private ArrayList<String> allParamNames = new ArrayList<String>();  
  11.     //实体信息  
  12.     private String body;  
  13.       
  14.     private byte[] arrayBody;  
  15.       
  16.     public String getParamValue(String _name){  
  17.         return param.get(_name);  
  18.     }  
  19.     public String getHeaderValue(String _name){  
  20.         return header.get(_name);  
  21.     }  
  22.       
  23.     public void addHeader(String _name,String _value) throws Exception{  
  24.         if(null != _name && null != _value ){  
  25.             header.put(_name, _value);  
  26.             allHeaderNames.add(_name);  
  27.         } else {  
  28.             throw new Exception("头信息请求参数非法");  
  29.         }  
  30.     }  
  31.       
  32.     public void addParam(String _name,String _value) throws Exception{  
  33.         if(null != _name && null != _value ){  
  34.             param.put(_name, _value);  
  35.             allParamNames.add(_name);  
  36.         } else {  
  37.             throw new Exception("请求参数非法");  
  38.         }  
  39.     }  
  40.       
  41.       
  42.     public ArrayList<String> getHeaderNames(){  
  43.         return allHeaderNames;  
  44.     }  
  45.     public  ArrayList<String> getParamNames(){  
  46.         return allParamNames;  
  47.     }  
  48.       
  49.     public void clearCache(){  
  50.         if(null != header){  
  51.             header.clear();  
  52.         }  
  53.         if(null != allHeaderNames){  
  54.             allHeaderNames.clear();  
  55.         }  
  56.         if(null != param){  
  57.             param.clear();  
  58.         }  
  59.         if(null != allParamNames){  
  60.             allParamNames.clear();  
  61.         }  
  62.           
  63.     }  
  64.       
  65.     public String getBody() {  
  66.         return body;  
  67.     }  
  68.   
  69.     public void setBody(String body) {  
  70.         this.body = body;  
  71.     }  
  72.   
  73.       
  74.     public byte[] getArrayBody() {  
  75.         return arrayBody;  
  76.     }  
  77.     public void setArrayBody(byte[] arrayBody) {  
  78.         this.arrayBody = arrayBody;  
  79.     }  
  80.     public Parameter(){  
  81.         clearCache();  
  82.     }  
  83.       
  84.   
  85. }  

3 响应请求封装类NetWorkResponseMsg:
  1. import java.io.IOException;  
  2. import java.io.InputStream;  
  3.   
  4. public class NetWorkResponseMsg {  
  5.       
  6.     private InputStream inputStream ;  
  7.       
  8.     private int responseCode = 200;  
  9.   
  10.     private String responseMsg = null;  
  11.       
  12.     public NetWorkResponseMsg() {  
  13.     }  
  14.   
  15.       
  16.     public NetWorkResponseMsg(InputStream inputStream, int responseCode) {  
  17.         this.inputStream = inputStream;  
  18.         this.responseCode = responseCode;  
  19.     }  
  20.   
  21.       
  22.     public NetWorkResponseMsg(InputStream inputStream, int responseCode,  
  23.             String responseMsg) {  
  24.         this.inputStream = inputStream;  
  25.         this.responseCode = responseCode;  
  26.         this.responseMsg = responseMsg;  
  27.     }  
  28.   
  29.     public String getResponseMsg() {  
  30.         return responseMsg;  
  31.     }  
  32.   
  33.     public void setResponseMsg(String responseMsg) {  
  34.         this.responseMsg = responseMsg;  
  35.     }  
  36.   
  37.   
  38.     public InputStream getInputStream() {  
  39.         return inputStream;  
  40.     }  
  41.   
  42.     public void setInputStream(InputStream inputStream) {  
  43.         this.inputStream = inputStream;  
  44.     }  
  45.   
  46.     public int getResponseCode() {  
  47.         return responseCode;  
  48.     }  
  49.   
  50.     public void setResponseCode(int responseCode) {  
  51.         this.responseCode = responseCode;  
  52.     }  
  53.       
  54.     public void closeStream(){  
  55.         try {  
  56.             if(inputStream != null){  
  57.                 inputStream.close();  
  58.             }  
  59.         } catch (IOException e) {  
  60.         }  
  61.     }  
  62.       


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值