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

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

具体情况如上图。

注意:

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

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

serverUtil:

  1. /**
  2. *网络通信核心类
  3. *@authorguxuede
  4. *
  5. */
  6. publicclassServerUtil{
  7. privatestaticStringhosturl/*="http://192.168.1.56:8080/CRMServer"*/;
  8. privatestaticDefaultHttpClienthttpClient;
  9. privatestaticintConnectionTimeout=5;//连接超时
  10. privatestaticintReadTimeOut=5;//读超时
  11. /**
  12. *初始化IpPort
  13. *@paramip
  14. *@paramport
  15. */
  16. publicstaticvoidinitIpPort(Stringip,Stringport){
  17. hosturl="http://"+ip+":"+port+"/CRMServer";
  18. ClientServiceFactory.initUri();
  19. }
  20. /**
  21. *初始化httpClient
  22. */
  23. publicstaticvoidinitHttpClient(){
  24. HttpParamsparams=newBasicHttpParams();
  25. HttpProtocolParams.setContentCharset(params,"utf-8");
  26. HttpProtocolParams.setHttpElementCharset(params,"utf-8");
  27. HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  28. HttpProtocolParams.setUserAgent(params,"HttpComponents/1.1");
  29. HttpConnectionParams.setConnectionTimeout(params,ConnectionTimeout*1000);
  30. HttpConnectionParams.setSoTimeout(params,ReadTimeOut*1000);
  31. SchemeRegistryschemeRegistry=newSchemeRegistry();
  32. schemeRegistry.register(newScheme("http",PlainSocketFactory.getSocketFactory(),80));
  33. schemeRegistry.register(newScheme("https",SSLSocketFactory.getSocketFactory(),443));
  34. ClientConnectionManagerconnectionManager=newThreadSafeClientConnManager(params,schemeRegistry);
  35. httpClient=newDefaultHttpClient(connectionManager,params);
  36. }
  37. publicstaticHttpClientgetHttpClient(){
  38. returnhttpClient;
  39. }
  40. publicstaticStringgetHosturl(){
  41. returnhosturl;
  42. }
  43. }


HttpUtil:

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

未完待续。。。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值