-
- 首先,我們要熟悉Android的HttpGet和HttpPost請求。其中Apache公司已經提供了兩個類,叫:HttpGet和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();
- }
-
這樣就向百度伺服器發送了一個HttpGet請求,請求的是百度的搜尋首頁,伺服器傳回來都是Html代碼,隻是浏覽器有解析HTML的功能,将HTML代碼轉換成所顯示的頁面,是以,列印出來的都是HTML代碼。
-
- //使用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();
- }