您的位置:首页 > 理论基础 > 计算机网络

【Android进阶学习】Http编程之HttpConnection

2012-03-11 20:11 351 查看
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();
}
}
}


本文出自 “IT的点点滴滴” 博客,请务必保留此出处http://liangruijun.blog.51cto.com/3061169/803159
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: