Android项目技术总结:网络连接总结

本项目通过httpClient进行客户端和服务器的网络连接,我稍稍的将客户端发送请求部分的网络总结了一下。

 

 

具体情况如上图。

注意:

1、各种请求在这里代表登录请求,任务请求等等url地址。

 

可以看出,整个网络部分, 最为关键的便为serverUtil和httpUtil两块,这两块的具体代码如下:

serverUtil:

  1. /** 
  2.  *  网络通信核心类 
  3.  * @author guxuede 
  4.  * 
  5.  */  
  6. public class ServerUtil {  
  7.     private static  String hosturl /*= "http://192.168.1.56:8080/CRMServer"*/;  
  8.     private static  DefaultHttpClient httpClient;  
  9.     private static int ConnectionTimeout = 5;// 连接超时  
  10.     private static int ReadTimeOut = 5;// 读超时  
  11.       
  12.     /** 
  13.      * 初始化IpPort 
  14.      * @param ip 
  15.      * @param port 
  16.      */  
  17.     public static void initIpPort(String ip,String port){  
  18.         hosturl="http://"+ip+":"+port+"/CRMServer";  
  19.         ClientServiceFactory.initUri();  
  20.     }  
  21.     /** 
  22.      * 初始化httpClient 
  23.      */  
  24.     public static void initHttpClient(){  
  25.         HttpParams params = new BasicHttpParams();  
  26.         HttpProtocolParams.setContentCharset(params, "utf-8");  
  27.         HttpProtocolParams.setHttpElementCharset(params, "utf-8");  
  28.         HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);  
  29.         HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");  
  30.   
  31.         HttpConnectionParams.setConnectionTimeout(params,ConnectionTimeout * 1000);  
  32.         HttpConnectionParams.setSoTimeout(params, ReadTimeOut * 1000);  
  33.   
  34.         SchemeRegistry schemeRegistry = new SchemeRegistry();  
  35.         schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));  
  36.         schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));  
  37.   
  38.         ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params,schemeRegistry);  
  39.           
  40.         httpClient = new DefaultHttpClient(connectionManager, params);  
  41.   
  42.     }  
  43.   
  44.     public static HttpClient getHttpClient() {  
  45.         return httpClient;  
  46.     }  
  47.   
  48.     public static String getHosturl() {  
  49.         return hosturl;  
  50.     }  
  51. }  


HttpUtil:

  1. public class HttpUtil {  
  2.     private static final String TAG=ActivityUtil.getTag(HttpUtil.class);  
  3.       
  4.     /** 
  5.      * 该方法可以将一个对象中所有属性和他们的值转换成键值对。 
  6.      * 以属性名为Key,属性的值为Value,存放入NameValuePair中。 
  7.      * 值为null的将不转换,且一个类中第一个属性不转换(因为考虑到很多类继承了Serializable,不想将serialVersionUID也无聊的转换进去); 
  8.      * 所以规定:要转换的类必须实现Serializable且设置serialVersionUID在类属性中第一个位置。 
  9.      * 参数l。指的是要向上递归几个父类。 
  10.      * l=1:只转换自己 
  11.      * l=2:转换自己和父类。 
  12.      * @param obj 要转换的对象 
  13.      * @param l   l=1:只转换自己  l=2:转换自己和父类。以此类推 
  14.      */  
  15.     public static void ObjectToNameValuePairs(Serializable obj,int l,List<NameValuePair> params){  
  16.         if(obj==null)  
  17.             return;  
  18.         Class<?> clss=obj.getClass();  
  19.         for(int i=0;i<l;i++){  
  20.             if(i > 0){  
  21.                 clss=(Class<?>) clss.getGenericSuperclass();  
  22.             }  
  23.             Field[] fields=clss.getDeclaredFields();  
  24.             if(fields.length < 2){  
  25.                 continue ;  
  26.             }  
  27.             for(int j=1;j < fields.length;j++){  
  28.                 fields[j].setAccessible(true);  
  29.                 Object o=null;  
  30.                 try {  
  31.                     o = fields[j].get(obj);  
  32.                 } catch (IllegalArgumentException e1) {  
  33.                     Log.w(TAG, e1);  
  34.                 } catch (IllegalAccessException e2) {  
  35.                     Log.w(TAG, e2);  
  36.                 }  
  37.                 if(o!=null){  
  38.                     params.add(new BasicNameValuePair(fields[j].getName(),o.toString()));  
  39.                 }  
  40.                 fields[j].setAccessible(false);  
  41.             }  
  42.         }  
  43.     }  
  44.       
  45.     /** 
  46.      * 向指定的uri发送post方法。将返回的信息转换成对象。 
  47.      * 抛出的InteractionException异常有以下种情况 
  48.      * msg_res_id=1  Request refused 
  49.      * msg_res_id=2 Request timeout 
  50.      * msg_res_id=3 Replies can not be resolved 
  51.      * msg_res_id=100> http访问服务端异常 
  52.      * msg_res_id=1001 没有登录或session失效 
  53.      * msg_res_id=1002 参数不正确导致服务端异常(sql异常,空指针) 
  54.      * @param uri           hosturi 
  55.      * @param params        附加参数 
  56.      * @return              转换的object 
  57.      * @throws InteractionException  
  58.      */  
  59.     public static Object executePost(String uri,List<NameValuePair> params) throws InteractionException{  
  60.         HttpClient httpclinet=ServerUtil.getHttpClient();  
  61.         HttpPost post=new HttpPost(uri);  
  62.         try {  
  63.             if(params!=null){  
  64.                 post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));  
  65.             }  
  66.         } catch (UnsupportedEncodingException e1) {  
  67.             Log.w(TAG, e1);  
  68.         }  
  69.         HttpResponse res=null;  
  70.         try {  
  71.             Long start=System.currentTimeMillis();  
  72.             Log.v("Post""Start:[URI:"+uri+"] [Params:"+params+"]");  
  73.             res = httpclinet.execute(post);  
  74.             Log.v("Post""Over:[URI:"+uri+"] [Cost Time:"+(System.currentTimeMillis()-start)+"]");  
  75.         } catch (Exception e) {  
  76.             Log.w(TAG, e);  
  77.             //极有可能会超时  
  78.             if(e instanceof HttpHostConnectException){  
  79.                 throw new InteractionException("Request refused", e ,1);  
  80.             }else{  
  81.                 throw new InteractionException("Request timeout", e ,2);  
  82.             }  
  83.         }  
  84.           
  85.         if(res.getStatusLine().getStatusCode()==HttpStatus.SC_OK){  
  86.             Header headercode=res.getFirstHeader("ResultCode");  
  87.             if(headercode!=null && headercode.getValue()!=null){  
  88.                 int mResultCode=Integer.parseInt(headercode.getValue());  
  89.                 Header reason=res.getFirstHeader("Reason");  
  90.                 if(reason!=null && reason.getValue()!=null){  
  91.                     //从返回头中获取服务端主动抛出的异常。如没有登录 参数不正确等异常  
  92.                     throw new InteractionException( reason.getValue() , mResultCode);  
  93.                 }  
  94.             }  
  95.             ObjectInputStream ois=null;  
  96.             try {  
  97.                 ois = new ObjectInputStream(res.getEntity().getContent());  
  98.                 Object obj = ois.readObject();  
  99.                 return obj;  
  100.             } catch (Exception e) {  
  101.                 Log.w(TAG, e);  
  102.                 //服务端返回了令人难以理解的内容  
  103.                 throw new InteractionException("Replies can not be resolved", e ,3);  
  104.             }finally{  
  105.                 if(ois!=null)  
  106.                     try {  
  107.                         ois.close();  
  108.                     } catch (IOException e) {  
  109.                         Log.w(TAG, e);  
  110.                     }  
  111.             }  
  112.         }else{  
  113.             //服务端发生异常  
  114.             throw new InteractionException("Request failure,Server exception",res.getStatusLine().getStatusCode());  
  115.         }  
  116.     }  
  117. }  

未完待续。。。

posted on 2016-09-08 14:00  miaozhenzhong  阅读(207)  评论(0编辑  收藏  举报

导航