2011年5月16日月曜日

AndroidStudyMemo=Using HttpURLConnection

for networking to work in any Android application, permission is required.Your

application needs to have the following statement in its AndroidManifest.xml file:

<uses-permission

android:name="android.permission.INTERNET"/>

 

Using HttpURLConnection

We can use the HttpURLConnection object to do a little reconnaissance on our URL before

we transfer too much data. HttpURLConnection retrieves some information about the

resource referenced by the URL object, including HTTP status and header information.

Some of the information you can retrieve from the HttpURLConnection includes the

length of the content, content type, and date-time information so that you can check to

see if the data changed since the last time you accessed the URL.

Here is a short example of how to use HttpURLConnection to query the same URL

previously used:

 

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

// ...

URL text = new URL(

"http://api.flickr.com/services/feeds/photos_public.gne

??id=26648248@N04&lang=en-us&format=atom");

HttpURLConnection http =

(HttpURLConnection)text.openConnection();

Log.i("Net", "length = " + http.getContentLength());

Log.i("Net", "respCode = " + http.getResponseCode());

Log.i("Net", "contentType = "+ http.getContentType());

Log.i("Net", "content = "+http.getContent());

 

The log lines demonstrate a few useful methods with the HttpURLConnection class. If the

URL content is deemed appropriate, you can then call http.getInputStream() to get

the same InputStream object as before. From there, reading from the network resource is

the same, but more is known about the resource.

0 件のコメント:

コメントを投稿