Android項目技術總結:網路連接總結

來源:互聯網
上載者:User

本項目通過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=2Request timeout * msg_res_id=3Replies can not be resolved * msg_res_id=100> http訪問服務端異常 * msg_res_id=1001 沒有登入或session失效 * msg_res_id=1002 參數不正確導致服務端異常(sql異常,null 指標) * @param urihosturi * @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());}}}

未完待續。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.