android中的HttpUrlConnection的使用之五

來源:互聯網
上載者:User

標籤:

在使用之三中,我簡單的介紹一下,get方式傳遞資料,而這裡我將簡單的介紹一下post方式。至於get方式與post方式有什麼不同,我先賣一個關子,等我先把兩個方式的關鍵代碼貼出來,我再來說明這兩種方式的不同和優缺點。

java代碼(首先說明一下,下面的代碼都是用戶端的代碼,也就是手機端的代碼)

get方式的代碼(出自使用之三)

 1     private void DoGet() throws Exception 2     { 3         Log.i("main", "1"); 4         url = url + "?name=" +name + "&age=" + age;  5         URL url = new URL(this.url); 6         Log.i("main", "2"); 7         HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection(); 8         httpurlconnection.setRequestMethod("GET"); 9         httpurlconnection.setReadTimeout(5000);10         11         12         13         //使用get方式,服務端只有一個輸出資料流,因此手機端只需要有一個輸入資料流就行14         BufferedReader br = new BufferedReader(new InputStreamReader(httpurlconnection.getInputStream()));15         StringBuffer sb = new StringBuffer();16         String string = null;17         while((string = br.readLine()) != null)18         {19             sb.append(string);20         }21         Log.i("main", sb.toString());22     }

post方式代碼

 1     private void Dopost() throws Exception 2     { 3         URL url = new URL(this.url); 4         HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection(); 5         httpurlconnection.setRequestMethod("POST"); 6         httpurlconnection.setReadTimeout(5000); 7          8         //注意這裡 有一個輸出資料流,因為使用方式post傳輸,在伺服器端有一個輸入資料流等著 9         OutputStream out = httpurlconnection.getOutputStream();10         String content = "name=" + name + "&age=" + age;11         out.write(content.getBytes());12         13         //其次伺服器端有一個輸出資料流,因此這裡必須有一個輸入資料流,否則線程會一直等著14         BufferedReader br = new BufferedReader(new InputStreamReader(httpurlconnection.getInputStream()));15         StringBuffer sb = new StringBuffer();16         String string = null;17         while((string = br.readLine()) != null)18         {19             sb.append(string);20         }21         Log.i("main", sb.toString());22         23     }

最後,我再來介紹一下get方式與post方式的區別:

1.get方式發送資料是通過URL發送,因此在初始化URL時,加上了name和age的值,這是因為get方式通過URL發送資料的;而post方式發送資料是通過輸出資料流,也就是伺服器端的輸入資料流來接收資料的。

2.get方式發送的資料相對來說是較小的,通常只有幾KB;相較於大一點的資料通常使用post方式,因為post是通過輸出資料流來發送資料的

3.get方式發送資料時,所有的資料全部通過URL而暴露出來,並不是很安全;而post是通過流通道來發送的,相對來比較安全

            

android中的HttpUrlConnection的使用之五

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.