Android 网络编程 HttpClient

介绍如何使用HttpClient发起GET或者POST请求

<pre name="code" class="java"><span style="font-size:18px;"><span style="color:#3366ff;">/**
 * @author Administrator
 *
 */</span>
public class HttpUtils {
	<span style="color:#009900;">//创建HttpClient对象</span>
	public static HttpClient httpClient = new DefaultHttpClient();
	<span style="color:#3333ff;">/**
	 * 
	 * @param url 发送请求的url
	 * @return  服务器响应字符串
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */</span>
	public static String getRequest(String url) throws ClientProtocolException, IOException{
		<span style="color:#009900;">//创建HttpGet对象</span>
		HttpGet httpGet = new HttpGet(url);
		<span style="color:#009900;">//发送GET请求</span>
		HttpResponse httpResponse = httpClient.execute(httpGet);
		<span style="color:#009900;">//如果服务器成功地返回响应</span>
		if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
			String result = EntityUtils.toString(httpResponse.getEntity());
			return result;
		}
		return null;
	}
	<span style="color:#3333ff;">/**
	 * 
	 * @param url 发送请求的url
	 * @param rawParams 请求参数
	 * @return 服务器响应字符串
	 * @throws ClientProtocolException
	 * @throws IOException
	 */</span>
	public static String postRequest(String url,List<NameValuePair> params) throws ClientProtocolException, IOException{
		<span style="color:#009900;">//创建HttpPost对象</span>
		HttpPost httpPost = new HttpPost(url);
		<span style="color:#009900;">//如果传递参数个数较多,可以对传递的参数进行封装</span>
<span style="color:#009900;">//		List<NameValuePair> params = new ArrayList<NameValuePair>();
//		for(String key:rawParams.keySet()){
//			params.add(new BasicNameValuePair(key, rawParams.get(key)));
//		}</span>
		httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); 
		<span style="color:#009900;">//发送post请求</span>
		HttpResponse httpResponse = httpClient.execute(httpPost);
		
		<span style="color:#009900;">//如果服务器成功地返回响应</span>
		if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
			String result = EntityUtils.toString(httpResponse.getEntity());
			return result;
		}
		return null;
	}</span>

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值