Android客戶端與服務器端交互方式總結

一、HttpClient 方式:

//第一步:創建一個客戶端實例
HttpClient httpClient = new DefaultHttpClient(); 
//第二步:創建Http請求
HttpPost  httpRequest = new HttpPost(url);  
//第三步: Entity作爲Http的request報文的一部分進行傳輸 
httpRequest.setEntity(new UrlEncodedFormEntity( nameValuePair ));  
//第四步:發送http的請求request,並接受服務器返回的response
HttpResponse response=httpClient.execute(httpRequest);

//第五步: 根據返回狀態碼,若成功(200)則獲取Entity,若失敗,則返回
if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)      
        result=EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
else
        result="登陸失敗!";  

二、HttpURLConnection方式

For example, to retrieve the webpage at http://www.android.com/:

 URL url = new URL("http://www.android.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
    finally {
     urlConnection.disconnect();
   }
 }
發佈了34 篇原創文章 · 獲贊 5 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章