Android—Http串連之GET/POST請求

來源:互聯網
上載者:User

 

Android—Http串連之GET/POST請求

   在Android SDK中提供了Apache HttpClient(org.apache.http.*)模組。在這個模組中涉及到兩個重要的類:HttpGet和HttpPost。

   建立步驟:  1、建立HttpGet(或HttpPost)對象,將要請求的URL通過構造方法傳入HttpGet(或HttpPost)對象中;   2、使用DefaultHttpClient類的execute方法發送HTTP GET或HTTP POST 請求,並返回HttpResponse對象;   3、通過HttpResponse介面的getEntity方法返迴響應資訊。   雖然兩者都是按這樣的步驟來實現的,但是實際中兩者又有些區別,具體代碼如下:      HTTP GET請求:   String url;   //第一步,建立HttpGet對象   HttpGet httpGet = new HttpGet(url);   //第二步,使用execute方法發送HTTP GET請求,並返回HttpResponse對象   httpResponse = new DefaultHttpClient().execute(httpGet);   if (httpResponse.getStatusLine().getStatusCode() == 200)   {        //第三步,使用getEntity方法活得返回結果        String result = EntityUtils.toString(httpResponse.getEntity());    }   HTTP POST請求:   String url;   //第一步,建立HttpPost對象   HttpPost httpPost = new HttpPost(url);  //設定HTTP POST請求參數必須用NameValuePair對象   List<NameValuePair> params = new ArrayList<NameValuePair>();   params.add(new BasicNameValuePair("bookname", etBookName.getText().toString()));   //設定httpPost請求參數   httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));   //第二步,使用execute方法發送HTTP GET請求,並返回HttpResponse對象   httpResponse = new DefaultHttpClient().execute(httpPost);   if (httpResponse.getStatusLine().getStatusCode() == 200)   {        //第三步,使用getEntity方法活得返回結果        String result = EntityUtils.toString(httpResponse.getEntity());    }上述就是對GET和POST方法的講解,兩者有相似的地方也有不同的地方,需要加以區別
相關文章

聯繫我們

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