您的位置:首页 > 理论基础 > 计算机网络

Android使用HTTP GET、HTTP POST获取网络数据

2014-01-06 16:40 549 查看
无论是使用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;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐