凡是接觸過android應用開發的,都離不開網路編程,android應用作為一個用戶端,沒有了服務端的服務是沒多大作為的,要跟服務端互動,必須要用到網路編程,就我接觸來說,android的網路編程有三種方法。
方法一、利用httpurlconnection,用法如下
利用HttpURLConnection對象,我們可以向網路發送請求參數.
String requestUrl = http://localhost:8080/itcast/contanctmanage.do;Map<String, String> requestParams = new HashMap<String, String>();requestParams.put("age", "12");requestParams.put("name", "中國"); StringBuilder params = new StringBuilder();for(Map.Entry<String, String> entry : requestParams.entrySet()){ params.append(entry.getKey()); params.append("="); params.append(URLEncoder.encode(entry.getValue(), "UTF-8")); params.append("&");}if (params.length() > 0) params.deleteCharAt(params.length() - 1);byte[] data = params.toString().getBytes();URL realUrl = new URL(requestUrl);HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();conn.setDoOutput(true);//發送POST請求必須設定允許輸出conn.setUseCaches(false);//不使用Cacheconn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive");//維持長串連conn.setRequestProperty("Charset", "UTF-8");conn.setRequestProperty("Content-Length", String.valueOf(data.length));conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());outStream.write(data);outStream.flush
方法二、利用httpclient,用法如下,傳參數
HttpClient client = new DefaultHttpClient(); //建立一個HttpClient HttpPost request = new HttpPost(); //執行個體化新的Http方法 request.setURI(new URI("http://code.google.com/android/")); // 設定HTTP參數 List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuepair("one","valueGoesHere")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); request.setEntity(formEntity); HttpResponse response = client.execute(request);//使用httpClient執行HTTP調用 BufferedReader in = new BufferedReader(new InputSteamReader(response.getEntity.getContent));//處理HTTP響應
方法三,利用androidhttpclient
經過實際項目,利用方法一的時候,第一串連伺服器,在connect的時候,要花比較長的時間,
而方法二在串連伺服器時,速度比較快,網路好時,3秒就串連上,
強力推薦用方法二,HttpClient。