Android使用HTTP GET、HTTP POST獲取網絡數據

無論是使用HttpGet,還是使用HttpPost,都必須通過如下3步來訪問HTTP資源。
1.創建HttpGet或HttpPost對象,將要請求的URL通過構造方法傳入HttpGet或HttpPost對象。
2.使用DefaultHttpClient類的execute方法發送HTTP GET或HTTP POST請求,並返回HttpResponse對象。
3.通過HttpResponse接口的getEntity方法返回響應信息,並進行相應的處理。
如果使用HttpPost方法提交HTTP POST請求,還需要使用HttpPost類的setEntity方法設置請求參數。
示例代碼:
 public static String connServerForResult(final String url) {
	HttpGet httpRequest = new HttpGet(url);
	String strResult = "";
	try {
	    HttpClient httpClient = new DefaultHttpClient();
	    HttpResponse httpResponse = httpClient.execute(httpRequest);
	    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		strResult = EntityUtils.toString(httpResponse.getEntity());
	    }
	} catch (ClientProtocolException e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	}
	return strResult;
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章