编写一个android 程序需要调用台式机(服务器)上的 tomcat 内的数据时:比如一个XML文件,或者是一个MP3文件。如何下载。
以下载一个XML文件为例:
首先搭建服务器:
1、搭建服务器使用tomcat。 建好放入文件,在手机浏览器测试是否可以访问,不能得话,关闭防火墙后再试,再不行就考虑 网络是否在局域网类的问题。
2、在配置文件中 打开权限
3、编写一个工具类:(记得要关闭BufferedReader )
public class HttpDownloader {
public String download(String urlStr) throws IOException
{
StringBuffer sb= new StringBuffer();
String line = null;
BufferedReader buffer =null;
try {
//创建一个URL对象
URL url =new URL(urlStr);
//创建一个HTTP连接
HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
//使用IO流读取数据
InputStream is= urlConn.getInputStream();
buffer=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while((line=buffer.readLine())!=null)
{
sb.append(line);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
buffer.close();
}
return sb.toString();
}
4、调用:
String xml=downloadXML("http://192.168.1.101:8080/MP3/resource.xml");
如果要将CML中的文件解释,就需要调用到SAX解析的知识。