android网络连接系列片之(二)----httpurlconnection

来源:互联网 发布:win7 iis php环境搭建 编辑:程序博客网 时间:2024/06/05 22:31

一、这是一个面向连接的协议,当然所有的http协议都是面向连接的

二、适用范围:

An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance.

这是google sdk上面的一句原话,httpURLConnection是可以传输任何类型的数据以及任何长度的数据,也可以用来传输事先不知道长度的数据。由此可见它的适用范围很广。

三、使用步骤:

Uses of this class follow a pattern:

  1. Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
  2. Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
  3. Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by getOutputStream().
  4. Read the response. Response headers typically include metadata such as the response body's content type and length, modified dates and session cookies. The response body may be read from the stream returned by getInputStream(). If the response has no body, that method returns an empty stream.
  5. Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.
以上是使用httpURLConnection的基本步骤,在开发中这些步骤是必不可少的,我们可以在这个的基础上面来增加一些内容,使得我们接收数据和发送数据更方便。这就是我前面说的那些大牛们对httpURLConnection的封装。

四、使用举例:

1、

  URL url = new URL("http://www.android.com/");   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();   try {     InputStream in = new BufferedInputStream(urlConnection.getInputStream());     readStream(in);    finally {     urlConnection.disconnect();   } }
上面是google sdk里面的一段代码,非常简洁。这里只是从服务器获取数据。注意reandStream(InputStream stream)这个函数要自己写

2、

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();   try {     urlConnection.setDoOutput(true);     urlConnection.setChunkedStreamingMode(0);     OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());     writeStream(out);     InputStream in = new BufferedInputStream(urlConnection.getInputStream());     readStream(in);    finally {     urlConnection.disconnect();   } }

这也是google  sdk上面的一段源代码,这里使用的是post方式来获取发送数据到服务器。然后再获取服务器发送的数据。

以上就是对httpURLConnection 的基本步骤进行了解,后面会在这个的基础上对它进行封装。


原创粉丝点击