HttpURLConnection是继承于URLConnection类,二者都是抽象类。其对象主要通过URL的openConnection方法获得的。
下面是具体的代码:
- package com.llingdududu.url;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import android.app.Activity;
- import android.os.Bundle;
- public class URLConnectionActivity extends Activity {
- String urlStr = "http://developer.android.com/";
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- try {
- //实例化URL
- URL url = new URL(urlStr);
- //使用HttpURLConnection打开连接
- HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
- //得到输入流对象
- InputStreamReader in = new InputStreamReader(httpConnection.getInputStream());
- BufferedReader bufReader = new BufferedReader(in);
- String lineStr = "";
- String resultStr = "";
- while ((lineStr = bufReader.readLine())!=null) {
- resultStr += lineStr + "\n";
- }
- System.out.println(resultStr);
- //关闭输入流
- in.close();
- //关闭连接
- httpConnection.disconnect();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }