天天看點

Android用戶端與伺服器資料互動

我們需要知道,Http協定是基于TCP協定的,而TCP協定是一種有連接配接,可靠的傳輸協定,如果丢失的話,會重傳。是以這樣的話,就不會有資料的丢失了。而Http協定有三種方法,Get,Post,Head方法,但是用的多的隻有Get和Post方法,Get方法是将請求參數放在請求頭中,是以請求的參數在URL中可見,而Post方法是将請求參數放在資料部分,是以在URL中不可見,Post相對來說保密,是以在送出重要資訊的時候,用的都是HttpPost方法來實作的.

1.使用HttpGet請求Baidu的首頁:
           
//使用HttpGet方法,把百度的首頁傳入
HttpGet hettpGet = new HttpGet("http://www.baidu.com/");
//使用預設的HttpClient
HttpClient hc = new DefaultHttpClient();
try {
//執行HttpGet方法,并且擷取傳回的響應
        HttpResponse response = hc.execute(hettpGet);
//如果響應碼為200則表示擷取成功,否則為發生錯誤
if (response.getStatusLine().getStatusCode() == 200) {
//s就是獲得的HTML代碼
        String s = EntityUtils.toString(response.getEntity());
        System.out.println(s);
}
} catch (ClientProtocolException e) 
{
        e.printStackTrace();
        } catch (IOException e) 
{        e.printStackTrace();
                   
           

//使用HttpPost發送請求

HttpPost httpPost = new HttpPost(url);        
//使用NameValuePaira儲存請求中所需要傳入的參數
List<NameValuePair> paramas = new ArrayList<NameValuePair>();
        paramas.add(new BasicNameValuePair("a", "a"));
        try {
 
HttpResponse httpResponse;
//将NameValuePair放入HttpPost請求體中
httpPost.setEntity(new UrlEncodedFormEntity(paramas,HTTP.UTF_8));
//執行HttpPost請求
httpResponse = new DefaultHttpClient().execute(httpPost);
//如果響應碼為200則表示擷取成功,否則為發生錯誤
if (httpResponse.getStatusLine().getStatusCode() == 200) {
String s = EntityUtils.toString(httpResponse .getEntity())}
           
} catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                 e.printStackTrace();
           } catch (ClientProtocolException e) {
                  // TODO Auto-generated catch block
                   e.printStackTrace();
            } catch (IOException e) {
            // TODO Auto-generated catch block
                 e.printStackTrace();
           } 
           

繼續閱讀