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方法的講解,兩者有相似的地方也有不同的地方,需要加以區別