读书人

Android透过URL获取网络数据

发布时间: 2012-10-28 09:54:44 作者: rapoo

Android通过URL获取网络数据

?

本实例主要是通过URL获取网络资源,在具体一点,就是简单介绍如何获取网页文本资源。获取网络资源还有获取图片、视频、音频……资源,框架基本相似。

?

实验时出现两点小问题:1、抛出Connection Refused的异常;2、出现乱码。

?

? ? ?3、 ?myString = new String(baf.toByteArray(), "GBK");

?? ? ? ? ? ? ? ? ? ? ? ?//myString = EncodingUtils.getString(baf.toByteArray(),?"GBK");

?? ? ? ? ? ? ? ? ? ? ? ?//myString = new String(baf.toByteArray());这个出现乱码,要在txt文件保存时选中utf-8

这三种任选一种。

当然,设置用户权限这个就不用说了!

Code:

package com.web.test; ?

?

import java.io.BufferedInputStream; ?

import java.io.InputStream; ?

import java.net.URL; ?

import java.net.URLConnection; ?

?

import org.apache.http.util.ByteArrayBuffer; ?

import org.apache.http.util.EncodingUtils; ?

?

import android.app.Activity; ?

import android.os.Bundle; ?

import android.widget.TextView; ?

/*?

?* 获取网络数据,这里展示如何获取网络上的一个poem.txt文本文件,架设了一个本地服务器?

?*/ ?

?

public class HelloWeb extends Activity { ?

?? ?@Override ?

?? ?public void onCreate(Bundle savedInstanceState) { ?

?? ? ? ?super.onCreate(savedInstanceState); ?

?? ? ? ?setContentView(R.layout.main); ?

?

?? ? ? ?TextView tv = new TextView(this); ?

?? ? ? ?String myString = null; ?

?

?? ? ? ?try { ?

?? ? ? ? ? ?URL uri = new URL("http://172.16.194.157:8080/my/my.txt");//注意,这里的URL地址必须为网络地址, ?

?? ? ? ? ? ?//URL uri = new URL("http://localhost:8080/my/poem.txt"); ?

?? ? ? ? ? ?//本地地址http://localhost:8080/my/poem.txt会报Connection Refused的异常 ?

?? ? ? ? ? ?URLConnection ucon = uri.openConnection(); ?

?? ? ? ? ? ?InputStream is = ucon.getInputStream(); ?

?? ? ? ? ? ?BufferedInputStream bis = new BufferedInputStream(is); ?

?? ? ? ? ? ?ByteArrayBuffer baf = new ByteArrayBuffer(100); ?

?? ? ? ? ? ?int current = 0; ?

?? ? ? ? ? ?while((current = bis.read()) != -1) { ?

?? ? ? ? ? ? ? ?baf.append((byte)current); ?

?? ? ? ? ? ?} ?

?

?? ? ? ? ? ?myString = new String(baf.toByteArray(), "GBK"); ?

?? ? ? ? ? ?//myString = EncodingUtils.getString(baf.toByteArray(), "GBK"); ?

?? ? ? ? ? ?//myString = new String(baf.toByteArray());这个出现乱码,要在txt文件保存时选中utf-8 ?

?? ? ? ?} catch(Exception e) { ?

?? ? ? ? ? ?myString = e.getMessage(); ?

?? ? ? ?} ?

?

?? ? ? ?tv.setText(myString); ?

?? ? ? ?this.setContentView(tv); ?

?? ?} ?

} ?

修改txt文本文件的编码格式

?

读书人网 >Android

热点推荐