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

Android文件下载 HttpURLConnection

2011-11-01 17:24 357 查看
步骤:通过new URL(目标网址字符串)得到URL对象url---->调用url的openConnection方法获得一个HttpURLConnection对象connection---->调用connection的getInputStream方法获得一个InputStream对象,访问结束,接下来就是io操作了。

实例:

16 public class DownloadDemoActivity extends Activity {

17 /** Called when the activity is first created. */

18 TextView textView;

19

20 Handler handler = new Handler(){

21

22 @Override

23 public void handleMessage(Message msg)

24 {

25 textView.setText((String)msg.obj);

26 }

27

28 };

29

30

31 @Override

32 public void onCreate(Bundle savedInstanceState) {

33 super.onCreate(savedInstanceState);

34 setContentView(R.layout.main);

35

36 textView = (TextView) findViewById(R.id.textView1);

37

38 }

39

40 public void buttonClick(View view)

41 {

42 new Thread(){

43

44 @Override

45 public void run()

46 {

47 StringBuffer stringBuffer = new StringBuffer();

48 HttpURLConnection connection = null;

49

50 try

51 {

52 URL url = new URL("http://www.baidu.com");

53 connection =

54 (HttpURLConnection) url.openConnection();

55

56 BufferedReader bReader = new BufferedReader

57 (new InputStreamReader(connection.getInputStream())) ;

58 String str;

59

60 while((str = bReader.readLine() ) != null)

61 {

62 stringBuffer.append(str);

63 }

64

65 }

66 catch (Exception e)

67 {

68 // TODO Auto-generated catch block

69 e.printStackTrace();

70 }finally{

71 connection.disconnect();

72 }

73

74 Message msg = handler.obtainMessage();

75 msg.obj = stringBuffer.toString();

76 msg.sendToTarget();

77

78 }

79

80

81

82 }.start();

83 }

84 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: