android用戶端與伺服器端互動過程

來源:互聯網
上載者:User

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服務對資源進行增、刪、改、查操作。

相關文章

聯繫我們

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