黑马程序员----------Android自学第二天总结(网络下载和解析)

-----------android培训java培训、java学习型技术博客、期待与您交流!------------ 

第六章:网络

1  下载,访问网页。InputStreamàInputStreamReaderàReader

URL

UrlConnection

HttpUrlConnection,

(网址中不允许有英文以外其他语言)

HttpClient(推荐使用)

 

2  解析

(1)  xml解析 domjavascript,pull(为安卓设计的),SAX

优点:清晰,数据量大,速度慢。

(2)  json解析

 数据量小,速度快,不太容易看懂。

WebView

<html>

<title>我的标题</title>

<meta http-equiv="Content-type" content="text/html; charset=gb2312" />

 

<head>

<table>

<tr>

<td></td>

<td></td>

 

</tr>

<tr>

</tr>

</table>

<ul>

<li></li>

</ul>

</head>

<body>

<a  href=’http://www.baidu.com’>百度</a>

 

</body>

</html>

1) 下载一张图片,用imageview显示

  url=new URL("http://list.image.baidu.com/t/image_category/galleryimg/funny/funnycartoon/xiao_ph.jpg") ;

//用的是URL这个类。构造方法中药写一个网址

input=url.openStream();

//通过openstream方法获取一个输入流。

bitmap=BitmapFactory.decodeStream(input);

//把这个流解析成一个bitmap类的对象。

imageView.setImageBitmap(bitmap);

input.close();

2) 下载一张图片到sd卡中。

  if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){//判断sd卡是否可用

File root=Environment.getExternalStorageDirectory();

File path=new File(root,"ima");

    File file=new File(path,"xiaopohai.png");

    try {

url=new URL("http://list.image.baidu.com/t/image_category/galleryimg/funny/funnycartoon/xiao_ph.jpg");

input=url.openStream();

 FileOutputStream output=new FileOutputStream(file,true);//不加true

    int t;

    byte [] buffer=new byte[1024];

    while((t=input.read(buffer))!=-1){

     output.write(buffer, 0, t);

    }

   input.close();

   output.close();

  Toast.makeText(MainActivity.this"复制完毕", Toast.LENGTH_LONG).show();

catch (MalformedURLException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

   

}else{

Toast.makeText(MainActivity.this"sd卡不可用", Toast.LENGTH_LONG).show();

return;

}

}

3) 例子HttpURLConnection这个类的使用。

下载时开启一个线程。

class  MyThread  implements  Runnable{

 

@Override

public void run() {

// TODO Auto-generated method stub

HttpURLConnection connection;

try {

connection = (HttpURLConnection) url.openConnection();

//要把url强制转化为httpurlconnection

connection.connect();

//连接。

if(connection==null){

return;

}

connection.setConnectTimeout(6000);

//设置超时时间 if(connection.getResponseCode()!=HttpURLConnection.HTTP_OK){

return;

}

InputStream  input=connection.getInputStream(); 

File  path=new File("/mnt/sdcard/download");

 if(!path.exists()){

     path.mkdirs();

    }

    File file=new File(path,str_file);

    OutputStream output=new FileOutputStream(file, true);

byte[] buffer=new  byte[1024];

if(input==null){

 return;

}

int t;

while((t=input.read(buffer))!=-1){

    output.write(buffer);

    

}

output.close();

input.close();

connection.disconnect();//断开连接。

MainActivity.getHandler().sendEmptyMessage(1);

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}}

}

4) webview控件的使用

String  data=loadData();

webview.loadDataWithBaseURL(null,data, "text/html", "utf-8", null);

//这个方法有四个参数

baseUrl

Url to resolve relative paths with, if null defaults to "about:blank"

data

A String of data in the given encoding.//一个字符串类型的。用html语言写的链接

mimeType

The MIMEType of the data. i.e. text/html. If null, defaults to "text/html"//数据类型

encoding

The encoding of the data. i.e. utf-8, us-ascii//编码

historyUrl

URL to use as the history entry. Can be null. 

public String loadData(){

     String t="";

     t+="<html>"

     t+="<head></head>";

     t+="<body><ul><li><a  href=http://www.baidu.com> </a></li><li><a  href='http://www.sina.com.cn/'> </a></li></ul>";

     t+="</body></html>";

     return t;

    }

5) pull解析

  InputStream  input=new FileInputStream(file);

XmlPullParser parser=Xml.newPullParser();

//创建一个解析器,用来解析之后的数据

    parser.setInput(input, "utf-8");

//把一个输入流放在解析器中

    int type=parser.getEventType();

//得到当前的数据类型。

    StringBuffer  buffer=new StringBuffer();

    String  name="";

    while(type!=XmlPullParser.END_DOCUMENT){

//如果不是文档的结束。     

     switch(type){

     case XmlPullParser.START_TAG:

     System.out.println("标记开始");

      name=parser.getName();

      parser.getName();

     //循环标记里的所有属性

     for(int i=0;i<parser.getAttributeCount();i++){

     //System.out.println("atts="+parser.getAttributeName(i)+":"+parser.getAttributeValue(i));

     buffer.append(parser.getAttributeValue(i)+"\n");

     }

     break;

     case XmlPullParser.TEXT:

     System.out.println("内容");

     if(!name.equals("age"))

     {

     buffer.append(parser.getText()+"\n");

     }

     break;

     case XmlPullParser.END_TAG:

     System.out.println("标记结束");

     break;

     }

     System.out.println("文档结束");

     type=parser.next();

    

    }textview.setText(buffer.toString());

6) 通过httpclient访问网络。

 // 通过httpclient访问网络。

String  address=ed01.getText().toString();

HttpClient   client =new DefaultHttpClient();

//在这里创建了一个httpclient对象。

//设置访问形式。

HttpGet  get=new HttpGet(address);

//访问网络有postget两种方式,这里用get方式。

try {

HttpResponse   response=client.execute(get);

//通过clientexecute方法,得到一个回应。如果这个对象不是空,那么在网上获取的全部信息,都从这个对象中获得、

if(response==null){

return;

}else{

Header[] headers= response.getAllHeaders();

//for (int i = 0; i < headers.length; i++) {

//System.out.println(headers[i].getName()+":"+headers[i].getValue());

//}

        HttpEntity   entity=response.getEntity();

//获取一个http的实体。  

if(entity==null){

         return;

        }

        InputStream  input=entity.getContent();

//终于得到一个输入流了。

if(input==null){

System.out.println("input==null="+input);

         return;

        }

     File  path=new File("/mnt/sdcard/download"); 

 if(!path.exists()){

 System.out.println("创建路径");

     path.mkdirs();

    }

String str_file=ed02.getText().toString();

    File file=new File(path,str_file);

    System.out.println("创建文件");

FileOutputStream output=new FileOutputStream(file, true);

byte[] buffer=new  byte[1024];

int t;

while((t=input.read(buffer))!=-1){

System.out.println("buffer write");

    output.write(buffer);

    

}

output.close();

input.close();

Toast.makeText(MainActivity.this"下载成功", Toast.LENGTH_SHORT).show(); }

(1) sax解析(和pull解析差不多,只不过它把解析的规则包装成了一个类,实现ContentHandler接口)

 

//设计解析的规则。

public class MySAXParser implements   ContentHandler{

    private  StringBuffer  buffer;

    private  String name;

public void setDocumentLocator(Locator locator) {

// TODO Auto-generated method stub

}

 

@Override

public void startDocument() throws SAXException {

// 文档的开始。

buffer=new StringBuffer();

buffer.append("开始解析。。。。\n");

}

 

@Override

public void endDocument() throws SAXException {

// TODO Auto-generated method stub

buffer.append("解析完毕");

}

@Override

public void startPrefixMapping(String prefix, String uri)

throws SAXException {

// TODO Auto-generated method stub

}

 

@Override

public void endPrefixMapping(String prefix) throws SAXException {

// TODO Auto-generated method stub

}

 

@Override

public void startElement(String uri, String localName, String qName,

Attributes atts) throws SAXException {

// TODO Auto-generated method stub

name=localName;

for (int i = 0; i < atts.getLength(); i++) {

buffer.append(atts.getValue(i));

}

}

 

@Override

public void endElement(String uri, String localName, String qName)

throws SAXException {

// TODO Auto-generated method stub

}

 

@Override

public void characters(char[] ch, int start, int length)

throws SAXException {

// TODO Auto-generated method stub

   String t=new String(ch, start, length);

   System.out.println("内容"+t);

   if(!name.equals("age")){

   buffer.append(ch,start,length);

   buffer.append("\n");

   }

}

public void ignorableWhitespace(char[] ch, int start, int length)

throws SAXException {

// TODO Auto-generated method stub

}

 

@Override

public void processingInstruction(String target, String data)

throws SAXException {

// TODO Auto-generated method stub

}

public void skippedEntity(String name) throws SAXException {

// TODO Auto-generated method stub

}

public  String getData(){

return buffer.toString();

}

}

 

(2) json解析

(1) 首先要导入jar包。(libs文件夹下)

(2) 其次,要创建路径

(3) 解析时候是以对象和数组的形式解析的。

 File  file=new File("/mnt/sdcard/students.json");

FileInputStream input;

try {

StringBuffer buffer=new StringBuffer();

input = new FileInputStream(file);

JsonReader  reader=new JsonReader(new InputStreamReader(input,"utf-8"));

//开始解析

reader.beginObject();

while(reader.hasNext()){

reader.beginObject();

while(reader.hasNext()){

String name=reader.nextName();

String value=reader.nextString();

String t_name="";

 //   buffer.append(name+"="+value+"\n");

if(name.equals("name")){

t_name="姓名";

}else if(name.equals("age")){

t_name="年龄";

}else if(name.equals("sex")){

t_name="性别";

}else{

continue;

}

buffer.append(t_name+"="+value+"\n");

}

reader.endObject();

}

reader.endArray();

textView.setText(buffer.toString());

catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值