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

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

 

 

具体情况如上图。

注意:

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

 

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

serverUtil:

/** * 网络通信核心类 * @author guxuede * */ public class ServerUtil { private static String hosturl /*= "http://192.168.1.56:8080/CRMServer"*/; private static DefaultHttpClient httpClient; private static int ConnectionTimeout = 5;// 连接超时 private static int ReadTimeOut = 5;// 读超时 /** * 初始化IpPort * @param ip * @param port */ public static void initIpPort(String ip,String port){ hosturl="http://"+ip+":"+port+"/CRMServer"; ClientServiceFactory.initUri(); } /** * 初始化httpClient */ public static void initHttpClient(){ HttpParams params = new BasicHttpParams(); HttpProtocolParams.setContentCharset(params, "utf-8"); HttpProtocolParams.setHttpElementCharset(params, "utf-8"); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpConnectionParams.setConnectionTimeout(params,ConnectionTimeout * 1000); HttpConnectionParams.setSoTimeout(params, ReadTimeOut * 1000); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params,schemeRegistry); httpClient = new DefaultHttpClient(connectionManager, params); } public static HttpClient getHttpClient() { return httpClient; } public static String getHosturl() { return hosturl; } }


HttpUtil:

public class HttpUtil { private static final String TAG=ActivityUtil.getTag(HttpUtil.class); /** * 该方法可以将一个对象中所有属性和他们的值转换成键值对。 * 以属性名为Key,属性的值为Value,存放入NameValuePair中。 * 值为null的将不转换,且一个类中第一个属性不转换(因为考虑到很多类继承了Serializable,不想将serialVersionUID也无聊的转换进去); * 所以规定:要转换的类必须实现Serializable且设置serialVersionUID在类属性中第一个位置。 * 参数l。指的是要向上递归几个父类。 * l=1:只转换自己 * l=2:转换自己和父类。 * @param obj 要转换的对象 * @param l l=1:只转换自己 l=2:转换自己和父类。以此类推 */ public static void ObjectToNameValuePairs(Serializable obj,int l,List<NameValuePair> params){ if(obj==null) return; Class<?> clss=obj.getClass(); for(int i=0;i<l;i++){ if(i > 0){ clss=(Class<?>) clss.getGenericSuperclass(); } Field[] fields=clss.getDeclaredFields(); if(fields.length < 2){ continue ; } for(int j=1;j < fields.length;j++){ fields[j].setAccessible(true); Object o=null; try { o = fields[j].get(obj); } catch (IllegalArgumentException e1) { Log.w(TAG, e1); } catch (IllegalAccessException e2) { Log.w(TAG, e2); } if(o!=null){ params.add(new BasicNameValuePair(fields[j].getName(),o.toString())); } fields[j].setAccessible(false); } } } /** * 向指定的uri发送post方法。将返回的信息转换成对象。 * 抛出的InteractionException异常有以下种情况 * msg_res_id=1 Request refused * msg_res_id=2 Request timeout * msg_res_id=3 Replies can not be resolved * msg_res_id=100> http访问服务端异常 * msg_res_id=1001 没有登录或session失效 * msg_res_id=1002 参数不正确导致服务端异常(sql异常,空指针) * @param uri hosturi * @param params 附加参数 * @return 转换的object * @throws InteractionException */ public static Object executePost(String uri,List<NameValuePair> params) throws InteractionException{ HttpClient httpclinet=ServerUtil.getHttpClient(); HttpPost post=new HttpPost(uri); try { if(params!=null){ post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); } } catch (UnsupportedEncodingException e1) { Log.w(TAG, e1); } HttpResponse res=null; try { Long start=System.currentTimeMillis(); Log.v("Post", "Start:[URI:"+uri+"] [Params:"+params+"]"); res = httpclinet.execute(post); Log.v("Post", "Over:[URI:"+uri+"] [Cost Time:"+(System.currentTimeMillis()-start)+"]"); } catch (Exception e) { Log.w(TAG, e); //极有可能会超时 if(e instanceof HttpHostConnectException){ throw new InteractionException("Request refused", e ,1); }else{ throw new InteractionException("Request timeout", e ,2); } } if(res.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ Header headercode=res.getFirstHeader("ResultCode"); if(headercode!=null && headercode.getValue()!=null){ int mResultCode=Integer.parseInt(headercode.getValue()); Header reason=res.getFirstHeader("Reason"); if(reason!=null && reason.getValue()!=null){ //从返回头中获取服务端主动抛出的异常。如没有登录 参数不正确等异常 throw new InteractionException( reason.getValue() , mResultCode); } } ObjectInputStream ois=null; try { ois = new ObjectInputStream(res.getEntity().getContent()); Object obj = ois.readObject(); return obj; } catch (Exception e) { Log.w(TAG, e); //服务端返回了令人难以理解的内容 throw new InteractionException("Replies can not be resolved", e ,3); }finally{ if(ois!=null) try { ois.close(); } catch (IOException e) { Log.w(TAG, e); } } }else{ //服务端发生异常 throw new InteractionException("Request failure,Server exception",res.getStatusLine().getStatusCode()); } } }


未完待续。。。

转载于:https://www.cnblogs.com/duancanmeng/archive/2012/02/28/2524633.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值