[置顶] android_学习—获取网络数据(图片,html)

一、使用URL访问网络资源——Androd中获取网络图片

URL对象代表着同意的资源定位器,她是只想互联网资源的指针,资源可以是简单的文件或目录,也可以是对更复杂的对象的引用,例如对数据库或者搜索引擎的查询;

 

URL提供了多个构造器,用于创建URl对象,一旦获得了URL对象后可以调用方法来获取资源;

 

下面提供一个获取网络图片的实例:

 

资源代码:

  <string name="btn_text">我显一下</string>

     <string name="error">下载图片失败!!</string>

布局文件:

 

<Button 

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/btn_text"

        android:id="@+id/showBtn"

        />

    

    <ImageView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/imageView"


 

 

service业务层编写:

 

package cn.haozi.service;

 

importjava.io.ByteArrayOutputStream;

importjava.io.IOException;

importjava.io.InputStream;

import java.net.HttpURLConnection;

importjava.net.URL;

 

public classimageService {

public staticbyte[] getImageDat(String  path) throwsException{

         

         URL url = new URL(path);

         

    

         HttpURLConnection conn=(HttpURLConnection) url.openConnection();

         //必须大写  设置响应头

    conn.setRequestMethod("GET");

    

    //设置延时

    conn.setConnectTimeout(5000);

  

    InputStream   inStream = conn.getInputStream();

    

    //字节数组输出流  

    ByteArrayOutputStream  bos = new ByteArrayOutputStream();

    

    byte[] buffer = new byte[1024];

    

    int len=0;

   

    while((len=inStream.read(buffer))!=-1){

           bos.write(buffer,0,len);

           

   }

    //封装

     byte[] data = bos.toByteArray();

         

         return data;

}

         

         

         

}

 


 

Activity编写:

 

package cn.haozi;

 

importcn.haozi.service.imageService;

importandroid.app.Activity;

importandroid.graphics.Bitmap;

importandroid.graphics.BitmapFactory;

importandroid.os.Bundle;

importandroid.util.Log;

importandroid.view.View;

importandroid.view.View.OnClickListener;

importandroid.widget.Button;

importandroid.widget.ImageView;

importandroid.widget.Toast;

 

public classnetTestActivity extends Activity implements OnClickListener {

   

         Button imageBtn;

         ImageView imageVIew;

    public void onCreate(BundlesavedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        

        

        findVIews();

    }

         private void findVIews() {

                   imageBtn = (Button)this.findViewById(R.id.Btn);

                   imageVIew  = (ImageView)this.findViewById(R.id.imageVIew);

                   

                   

                  imageBtn.setOnClickListener(this);

                   

         }

         

         public void onClick(View arg0) {

          

                     Stringpath="http://hiphotos.baidu.com/5335360123/pic/item/b4f722cada91fa5a7f3e6fc0.jpg";

                     

                     

                     try {

                            byte[] data =imageService.getImageDat(path);

                            Bitmap bitmap =BitmapFactory.decodeByteArray(data, 0, data.length);

                            imageVIew.setImageBitmap(bitmap);

                   } catch (Exception e) {

                            

                            Log.e("TAG",e.toString());

                            Toast.makeText(this,R.string.error,Toast.LENGTH_LONG ).show();

                   }

                   

                   

                   

         }

    

    

}


 

 

清单文件的修改:增添网络访问权限

<uses-permission android:name="android.permission.INTERNET"/>


 

 

运行效果:

            [置顶] android_学习—获取网络数据(图片,html)_第1张图片                   

 

 

二、Android获取网页html代码;

 

布局文件:

 

<Button 

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/btn_text"

        android:id="@+id/showBtn"

        />

    

    <ImageView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/imageView"

        />   


 

代码:在前面的ImageService.getImage()方法基础上修改即可

public class HtmlService {

    /**

     * 获取给定路径的html代码

     * @param path 网页路径

     * @return

     * @throws Exception

     */

    public static String getHtml(String path) throws Exception{

       URL url = new URL(path);

       //get //post

       HttpURLConnection conn =(HttpURLConnection)url.openConnection();

       conn.setRequestMethod("GET");

conn.setConnectTimeout(5*1000);

       InputStream inStream = conn.getInputStream();

       

       ByteArrayOutputStream outStream = new ByteArrayOutputStream();

       byte[] buffer = new byte[1024];

       int len = 0;

       while( (len = inStream.read(buffer)) !=-1 ){

           outStream.write(buffer, 0, len);

       }

       byte[] data = outStream.toByteArray();//网页的二进制数据

       outStream.close();

       inStream.close();

       return new String(data, "gb2312");

    }

}

Activity的按钮点击事件修改为:

public void onClick(View v) {

    String path = pathText.getText().toString();

    try {

       String htmlcode = HtmlService.getHtml(path);

       resultView.setText(htmlcode);

    } catch (Exception e) {

       Log.e(TAG, e.toString());

       Toast.makeText(ShowHtmlActivity.this, R.string.error, 1).show();

    }

}


 

程序运行视图:

 [置顶] android_学习—获取网络数据(图片,html)_第2张图片

你可能感兴趣的:(html,android,exception,网络,String,layout)