码迷,mamicode.com
首页 > Web开发 > 详细

访问网络之HttpClient和HttpUrlConnection

时间:2015-03-04 13:00:47      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:网络

HttpClient对比HttpUrlConnection有比较丰富的api,但是不利于扩展和升级,加上android团队在优化HttpClient方面并不积极。

我比较倾向使用HttpUrlConnection,下面还是把两种访问网络的方法列出来以作比较。

HttpClient:

public String httpGet(String url, String params) throws Exception
	{
		String response = null; //返回信息
		//拼接请求URL
		if (null!=params&&!params.equals(""))
		{
			url += "?" + params;
		}
		
		int timeoutConnection = 3000;  
		int timeoutSocket = 5000;  
		HttpParams httpParameters = new BasicHttpParams(); 
	   <span style="white-space:pre">	</span>HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
	    <span style="white-space:pre">	</span>HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);  
	    
		// 构造HttpClient的实例
		HttpClient httpClient = new DefaultHttpClient(httpParameters);  
		// 创建GET方法的实例
		HttpGet httpGet = new HttpGet(url);
		try
		{
			HttpResponse httpResponse = httpClient.execute(httpGet);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) //SC_OK = 200
			{
				// 获得返回结果
				response = EntityUtils.toString(httpResponse.getEntity());
			}
			else
			{
				response = "返回码:"+statusCode;
			}
		} catch (Exception e)
		{
			throw new Exception(e);
		} 
		return response;
	}
1.首先设置连接超时和读取超时时间,并且使用HttpConnectionParams把这两个参数设置到HttpParams中。

2.之后根据HttpParams获取HttpClient实例。

3.根据Url获取HttpGet实例。

4.HttpClient执行HttpGet获取返回值HttpResponse。

5.读取HttpResponse中的数据。

public String httpPost(String url, List<Parameter> params) throws Exception
	{
		String response = null;
		int timeoutConnection = 3000;  
		int timeoutSocket = 5000;  
		HttpParams httpParameters = new BasicHttpParams();
	    <span style="white-space:pre">	</span>HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
	    <span style="white-space:pre">	</span>HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);  
		// 构造HttpClient的实例
		HttpClient httpClient = new DefaultHttpClient(httpParameters);  
		HttpPost httpPost = new HttpPost(url);
		if (params.size()>=0)
		{
			//设置httpPost请求参数
			httpPost.setEntity(new UrlEncodedFormEntity(buildNameValuePair(params),HTTP.UTF_8));
		}
		//使用execute方法发送HTTP Post请求,并返回HttpResponse对象
		HttpResponse httpResponse = httpClient.execute(httpPost);
		int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK)
        {
            //获得返回结果
            response = EntityUtils.toString(httpResponse.getEntity());
        } else {
            response = "返回码:" + statusCode;
        }
        return response;
	}
	
	/**
	 * 把Parameter类型集合转换成NameValuePair类型集合
	 * @param params 参数集合
	 * @return
	 */
	private List<BasicNameValuePair> buildNameValuePair(List<Parameter> params)
	{
		List<BasicNameValuePair> result = new ArrayList<BasicNameValuePair>();
		for (Parameter param : params)
		{
			BasicNameValuePair pair = new BasicNameValuePair(param.getName(), param.getValue());
			result.add(pair);
		}
		return result;
	}
}
设置了Post的请求参数post方法和get方法其实差不多,主要区别是调用了HttpPost.setEntity( )方法设置了post参数。

注意下设置参数的过程,首先新建了UrlEncodedFormEntity,新建UrlEncodedFormEntity又需要BasicNameValuePair类型的list,

方法buildNameValuePair完成了params到BasicNameValuePair的转换。

HttpUrlConnection:

 public static void sendHttpRquest(final String address, final HttpCallBackListener listener) {
        new Thread(new Runnable() {
            HttpURLConnection connection = null;
            @Override
            public void run() {
                try{
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream inputstream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));
                    StringBuilder responsStr = new StringBuilder();
                    String line;
                    while((line = reader.readLine())!=null) {
                        responsStr.append(line);
                    }
                    if (listener != null) {
                        listener.onFinish(responsStr.toString());
                    }
                }catch(Exception e) {
                    if (listener != null) {
                        listener.onError(e);
                    }
                }
                finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
1.HttpUrlConnection访问网络的方式是先根据地址创建Url对象。

2.根据Url对象获取HttpUrlConnection对象,并且设置连接超时和访问超时时间。

3.之后就可以的到数据的读取流了。

4.根据读取流读取相应的数据。

这里使用了回调方法的形式读取取得的数据。



访问网络之HttpClient和HttpUrlConnection

标签:网络

原文地址:http://blog.csdn.net/superharder/article/details/44057431

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!