Android开发之Http通信HttpClient接口

来源:互联网 发布:淘宝联盟赚钱吗 编辑:程序博客网 时间:2024/03/29 17:03

Android开发之Http通信

HttpClient接口

/*

 *  Android开发之Http通信HttpClient接口

 *  北京Android俱乐部群:167839253

 *  Created on: 2012-5-10

 *  Author: blueeagle

 *  Email: liujiaxiang@gmail.com

 */

HttpClient接口

       Apache提供了HttpClient接口,其对java.net中的类做了封装和抽象。更适合我们在Android上开发联网应用。要使用HttpClient还需要了解一些类:

1.       ClientConnectionManager接口

此接口是客户端连接浏览器的接口,提供如下的抽象方法:

 

Public Methods

abstract void

closeExpiredConnections() //关闭所有无效超时的连接

Closes all expired connections in the pool.

abstract void

closeIdleConnections(long idletime, TimeUnit tunit) //关闭空闲的连接

Closes idle connections in the pool.

abstract SchemeRegistry

getSchemeRegistry() //得到一个SchemeRegistry

Obtains the scheme registry used by this manager.

abstract void

releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit)

Releases a connection for use by others.//释放一个连接

abstract ClientConnectionRequest

requestConnection(HttpRoute route, Object state)//请求一个新的连接

Returns a new ClientConnectionRequest, from which a ManagedClientConnection can be obtained or the request can be aborted.

abstract void

shutdown() //关闭管理器并释放资源

Shuts down this connection manager and releases allocated resources.

 

 

2.       DefaultHttpClient

DefaultHttpClient是默认的一个Http客户端,可以使用它创建一个Http连接。

This class replaces HttpClient in HttpClient 3

创建一个DefaultHttpColient的代码如下:

HttpClient httpclient = new DefaultHttpClient();

 

3.       HttpResponse

HttpResponse是一个Http连接响应,当执行一个Http连接后,就会返回一个HttpResponse,可以通过HttpResponse获得一些响应信息。例如,请求一个HTTP连接并获得该请求是否成功的代码:

HttpClient httpclient = new DefaultHttpClient();

HttpResponse httpResponse = httpclient.execute(httpRequest);

if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.sc_OK){

        //连接成功

}

 

后继将附上GET以及POST方式的代码。代码基本上跟HttpURLConnection的代码类似。