一起学android之Apache接口(17)

Apache HttpClient是一个开源项目,为客户端的HTTP编程提供高效、最新、功能丰富的工具包支持。


在Apache HttpClient库中,我们常用的对网络连接有用的包主要有以下几类:

-org.apache.http.HttpResponse

-org.apache.http.client.HttpClient

-org.apache.http.client.methods.HttpGet

-org.apache.http.impl.client.DefaulfHttpClient

HttpClient httpclient=new DefaultHttpClient();


如果是从服务器检索信息,需要使用HttpGet类的构造器,例如以下代码:

<span style="font-size:18px;">HttpGet request=new HttpGet("http://google.com");</span>
然后用HttpClient类的execut()方法中的HttpGet对象来检索HttpResponse对象,例如下面代码:

<span style="font-size:18px;">HttpResponse response=client.execute(request);</span>
最后读取已检索的响应,例如下面代码:

<span style="font-size:18px;">BufferedReader rd = new BufferedReader(new InputStreamReader(response
				.getEntity().getContent()));
		String line="";
		while ((line=rd.readLine())!=null) {
			System.out.println(line);
		}</span>


在Android系统中,可以采用HttpPost和HttpGet来封装Post请求和Get请求,然后使用HttpClient的execut()方法发送Post或者Get请求并返回服务器的响应数据。

Apache连网的基本流程如下:

1、设置连接和读取超时时间,并新建HttpClient对象,例如下面代码:

<span style="font-size:18px;">HttpParams httpParames=new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParames, 2000);
		HttpConnectionParams.setSoTimeout(httpParames, 2000);
		HttpClient httpClient=new DefaultHttpClient(httpParames);</span>

2、实现Get请求,例如下面代码:

<span style="font-size:18px;">HttpGet get = new HttpGet(uri);
		if (headers != null) {
			Set<String> setHead = headers.keySet();
			Iterator<String> iteratorHead = setHead.iterator();
			while (iteratorHead.hasNext()) {
				String headerName = iteratorHead.next();
				String headerValue = (String) headers.get(headerName);
				get.setHeader(headerName, headerValue);
			}

		}
		response = httpClient.execute(get);</span>
3、实现Post发送请求处理,例如下面代码:

<span style="font-size:18px;">HttpPost post = new HttpPost(uri);
		Set<String> setHead = headers.keySet();
		Iterator<String> iteratorHead = setHead.iterator();
		while (iteratorHead.hasNext()) {
			String headName = iteratorHead.next();
			String headValue = (String) headers.get(headName);
			post.setHeader(headName, headValue);
		}

		ContentProducer cp = new ContentProducer() {

			@Override
			public void writeTo(OutputStream outstream) throws IOException {
				Writer writer = new OutputStreamWriter(outstream, "UTF-8");
				writer.write(requestBody);
				writer.flush();
				writer.close();
			}
		};
		HttpEntity entity = new EntityTemplate(cp);
		post.setEntity(entity);
		response = httpClient.execute(post);</span>
通常的Http实体需要在执行上下文的时候动态生成的。HttpClient的提供使用EntityTemplate实体类和ContentProducer接口支持动态实体。ContentProducer中是通过写需求的内容到一个输出流,每次请求的时候都会产生。因此,通过EntityTemplate创建实体通常是独立的,重复性好。

4、通过Response响应请求,例如下面代码:

<span style="font-size:18px;">if(response.getStatusLine().getStatusCode()==200){
			byte[] result=EntityUtils.toByteArray(response.getEntity());
			if(result!=null){
				String str=new String(result,"UTF-8");
			}
		}</span>
上面这段代码如果直接调用toString()方法,可能会导致某些中文字符出现乱码的情况,所以使用toByteArray()方法,如果需要转换成String对象,可以先调用EntityUtils.toByteArray()方法,将消息实体转成byte的数组,再由new String[byte[] bArray]转换成字符串。

以上几个步骤就实现了连网处理数据交互。


Apache的核心功能是HttpClient,通过下面几行代码就能发出一个简单的Get请求并打印响应结果:

<span style="font-size:18px;">try {
			//创建一个默认的HttpClient
			HttpClient httpClient=new DefaultHttpClient();
			//创建一个Get请求
			HttpGet request=new HttpGet(uri);
			//发送Get请求,并响应内容转换成字符串
			String response=httpClient.execute(request,new BasicResponseHandler());
		} catch (Exception e) {
			e.printStackTrace();
		}</span>

如果同时有多个请求需要处理时,我们可以使用多线程,HttpClient提供了创建线程安全对象的API,例如下面代码:

<span style="font-size:18px;">private static final String CHARSET=HTTP.UTF_8;
	private static HttpClient httpClient;
	private HttpTest(){
	}
	public static synchronized HttpClient getHttpClient(){
		if(null==httpClient){
			HttpParams params=new BasicHttpParams();
			//设置参数
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);
			HttpProtocolParams.setUserAgent(params, "Mozilla/5.0(Linux,U;Android 4.0;en-us;.....)");
			//从连接池中取连接的超时时间
			ConnManagerParams.setTimeout(params, 2000);
			//连接超时
			HttpConnectionParams.setConnectionTimeout(params,2000);
			//请求超时
			HttpConnectionParams.setSoTimeout(params, 2000);
			//设置HttpClient支持HTTP和HTTPS两种模式
			SchemeRegistry sr=new SchemeRegistry();
			sr.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			sr.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 440));
			//使用线程安全的连接管理来创建HttpClient
			ClientConnectionManager ccm=new ThreadSafeClientConnManager(params, sr);
			httpClient=new DefaultHttpClient(ccm,params);
			
		}
		return httpClient;
	}</span>

在上面代码中,使用ThreadSafeClientConnManager 来创建线程安全的HttpClent。






转载请注明出处:http://blog.csdn.net/hai_qing_xu_kong/article/details/42836319 情绪控_








你可能感兴趣的:(httpclient,http,android,网络,android网络编程)