1 //建立一個http用戶端
2 HttpClient client=new DefaultHttpClient();
3 //建立一個GET請求
4 HttpGet httpGet=newHttpGet("http://www.store.com/products");
5 //向伺服器發送請求並擷取伺服器返回的結果
6 HttpResponse response=client.execute(httpGet);
7 //返回的結果可能放到InputStream,http Header中等。
8 InputStream inputStream=response.getEntity().getContent();
9 Header[] headers=response.getAllHeaders();
通過解析伺服器返回的流,我們可以將它轉為字串,擷取相應的資料。
第二步可以向伺服器增加商品,同樣的道理,我們建立一個POST請求,帶上相關的商品資訊即可。
01 //建立一個http用戶端
02 HttpClient client=new DefaultHttpClient();
03 //建立一個POST請求
04 HttpPost httpPost=newHttpPost("http://www.store.com/product");
05 //組裝資料放到HttpEntity中發送到伺服器
06 final List dataList = new ArrayList();
07 dataList.add(new BasicNameValuePair("productName","cat"));
08 dataList.add(new BasicNameValuePair("price","14.87"));
09 HttpEntity entity = new UrlEncodedFormEntity(dataList,"UTF-8");
10 httpPost.setEntity(entity);
11 //向伺服器發送POST請求並擷取伺服器返回的結果,可能是增加成功返回商品ID,或者失敗等資訊
12 HttpResponse response=client.execute(httpPost);
第三步是如果修改商品資訊,我們只需要建立一個PUT請求,帶上要修改的參數即可。本例假設第三步中增加的商品返回ID為1234,下面將為商品的價格修改為11.99.
01 //建立一個http用戶端
02 HttpClient client=new DefaultHttpClient();
03 //建立一個PUT請求
04 HttpPut httpPut=new HttpPut("http://www.store.com/product/1234");
05 //組裝資料放到HttpEntity中發送到伺服器
06 final List dataList = new ArrayList();
07 dataList.add(new BasicNameValuePair("price","11.99"));
08 HttpEntity entity = new UrlEncodedFormEntity(dataList,"UTF-8");
09 httpPut.setEntity(entity);
10 //向伺服器發送PUT請求並擷取伺服器返回的結果,可能是修改成功,或者失敗等資訊
11 HttpResponse response=client.execute(httpPut);
第四步我們把上面增加的商品刪除,只需要向伺服器發送一個DELETE請求即可。
1 //建立一個http用戶端
2 HttpClient client=new DefaultHttpClient();
3 //建立一個DELETE請求
4 HttpDelete httpDelete=newHttpDelete("http://www.store.com/product/1234");
5 //向伺服器發送DELETE請求並擷取伺服器返回的結果,可能是刪除成功,或者失敗等資訊
6 HttpResponse response=client.execute(httpDelete);
好了,就這麼簡單,這樣就實現了從android用戶端調用Rest服務對資源進行增、刪、改、查操作。