HttpURLConnection是继承于URLConnection类,二者都是抽象类。其对象主要通过URL的openConnection方法获得的。     

下面是具体的代码:

  1. package com.llingdududu.url;  
  2.  
  3. import java.io.BufferedReader;  
  4. import java.io.InputStreamReader;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7.  
  8. import android.app.Activity;  
  9. import android.os.Bundle;  
  10.  
  11. public class URLConnectionActivity extends Activity {  
  12.     String urlStr = "http://developer.android.com/";  
  13.     /** Called when the activity is first created. */ 
  14.     @Override 
  15.     public void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.main);  
  18.           
  19.         try {  
  20.             //实例化URL  
  21.             URL url = new URL(urlStr);  
  22.             //使用HttpURLConnection打开连接    
  23.             HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();  
  24.             //得到输入流对象  
  25.             InputStreamReader in = new InputStreamReader(httpConnection.getInputStream());  
  26.             BufferedReader bufReader = new BufferedReader(in);   
  27.             String lineStr = "";  
  28.             String resultStr = "";  
  29.             while ((lineStr = bufReader.readLine())!=null) {  
  30.                 resultStr += lineStr + "\n";                  
  31.             }  
  32.               
  33.             System.out.println(resultStr);  
  34.             //关闭输入流  
  35.             in.close();  
  36.             //关闭连接   
  37.             httpConnection.disconnect();  
  38.         } catch (Exception e) {  
  39.             // TODO Auto-generated catch block  
  40.             e.printStackTrace();  
  41.         }   
  42.     }