Android学习笔记(十一)-从Internet获取数据

来源:互联网 发布:液晶电视清晰知乎 编辑:程序博客网 时间:2024/05/07 12:14

URL(Uniform Resource Locator)对象代表统一资源定位器,它是指向互联网“资源”的指针。URL可以由协议名、主机、端口和资源组成。通过url.openConnection()可以获取一个HttpURLConnection对象,通过这个对象的getInputStream()方法就可以获取网络上的数据了,如图片、网页内容等,这跟在J2SE中是一样的。

Android应用要想访问网络上的数据,还需要在AndroidManifest.xml文件中添加访问权限:

<!-- 访问internet权限 -->
<uses-permission android:name="android.permission.INTERNET"/>

下面介绍一个通过URL访问图片和Html的实例:


布局文件layout/main.xml

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7.     <TextView  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="@string/urlpath"  
  11.         />  
  12.     <EditText  
  13.         android:id="@+id/urlpath"  
  14.         android:layout_width="fill_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="http://www.baidu.com/img/baidu_sylogo1.gif"  
  17.         />  
  18.     <Button  
  19.         android:id="@+id/imagebutton"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:text="@string/imagebutton"  
  23.         />  
  24.     <Button  
  25.         android:id="@+id/htmlbutton"  
  26.         android:layout_width="wrap_content"  
  27.         android:layout_height="wrap_content"  
  28.         android:text="@string/htmlbutton"  
  29.         />  
  30.     <ImageView  
  31.         android:id="@+id/showimage"  
  32.         android:layout_width="fill_parent"  
  33.         android:layout_height="300dip"  
  34.         android:scaleType="fitCenter"  
  35.         />  
  36.     <ScrollView  
  37.         android:layout_width="fill_parent"  
  38.         android:layout_height="fill_parent">  
  39.         <EditText  
  40.             android:id="@+id/showhtml"  
  41.             android:minLines="5"  
  42.             android:layout_width="fill_parent"  
  43.             android:layout_height="wrap_content"  
  44.             />  
  45.     </ScrollView>  
  46.       
  47. </LinearLayout>  
数据文件:values/strings.xml

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="hello">Hello World, URLActivity!</string>  
  4.     <string name="app_name">URL测试</string>  
  5.     <string name="urlpath">请输入图片网络地址</string>  
  6.     <string name="imagebutton">显示图片</string>  
  7.     <string name="htmlbutton">显示文本</string>  
  8.     <string name="error">获取图片失败</string>  
  9. </resources>  

Activity,URLActivity.java

[java] view plaincopy
  1. package com.geniusxiaoyu.url;  
  2.   
  3. import android.app.Activity;  
  4. import android.graphics.Bitmap;  
  5. import android.graphics.BitmapFactory;  
  6. import android.os.Bundle;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9. import android.widget.Button;  
  10. import android.widget.EditText;  
  11. import android.widget.ImageView;  
  12. import android.widget.Toast;  
  13.   
  14. import com.geniusxiaoyu.service.URLService;  
  15.   
  16. public class URLActivity extends Activity {  
  17.     private static final String TAG = "URLActivity";  
  18.     private EditText pathText;  
  19.     private EditText htmlText;  
  20.     private ImageView imageView;  
  21.     /** Called when the activity is first created. */  
  22.     @Override  
  23.     public void onCreate(Bundle savedInstanceState) {  
  24.         super.onCreate(savedInstanceState);  
  25.         setContentView(R.layout.main);  
  26.           
  27.         pathText = (EditText)findViewById(R.id.urlpath);  
  28.         htmlText = (EditText)findViewById(R.id.showhtml);  
  29.         imageView = (ImageView)findViewById(R.id.showimage);  
  30.         Button imagebutton = (Button)findViewById(R.id.imagebutton);  
  31.         //添加点击事件  
  32.         imagebutton.setOnClickListener(new View.OnClickListener() {  
  33.               
  34.             @Override  
  35.             public void onClick(View v) {  
  36.                 String path = pathText.getText().toString();  
  37.                 //显示与隐藏组件  
  38.                 htmlText.setVisibility(View.GONE);  
  39.                 imageView.setVisibility(View.VISIBLE);  
  40.                 try {  
  41.                     byte[] data = URLService.getBitData(path);  
  42.                     Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);//生成位图  
  43.                     imageView.setImageBitmap(bitmap);//显示图片  
  44.                 } catch (Exception e) {  
  45.                     Toast.makeText(URLActivity.this, R.string.error, 1).show();  
  46.                     Log.e(TAG, e.toString());  
  47.                 }  
  48.             }  
  49.         });  
  50.           
  51.         Button htmlbutton = (Button)findViewById(R.id.htmlbutton);  
  52.         //添加点击事件  
  53.         htmlbutton.setOnClickListener(new View.OnClickListener() {  
  54.               
  55.             @Override  
  56.             public void onClick(View v) {  
  57.                 String path = pathText.getText().toString();  
  58.                 //显示与隐藏组件  
  59.                 imageView.setVisibility(View.GONE);  
  60.                 htmlText.setVisibility(View.VISIBLE);  
  61.                 try {  
  62.                     byte[] data = URLService.getBitData(path);  
  63.                     String html = new String(data);  
  64.                     //显示文本  
  65.                     htmlText.setText(html);  
  66.                 } catch (Exception e) {  
  67.                     Toast.makeText(URLActivity.this, R.string.error, 1).show();  
  68.                     Log.e(TAG, e.toString());  
  69.                 }  
  70.             }  
  71.         });  
  72.           
  73.     }  
  74. }  

URLService.java

[java] view plaincopy
  1. package com.geniusxiaoyu.service;  
  2.   
  3. import java.io.InputStream;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.URL;  
  6.   
  7. import com.geniusxiaoyu.utils.StreamTool;  
  8.   
  9. public class URLService {  
  10.   
  11.     /** 
  12.      * 获取图片数据 
  13.      * @param path 
  14.      * @return 
  15.      * @throws Exception 
  16.      */  
  17.     public static byte[] getBitData(String path) throws Exception{  
  18.         URL url = new URL(path);  
  19.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  20.         conn.setConnectTimeout(1000 * 5);  
  21.         conn.setRequestMethod("GET");  
  22.         InputStream is = conn.getInputStream();  
  23.         return StreamTool.readInputStream(is);  
  24.     }  
  25. }  

StreamTool.java

[java] view plaincopy
  1. package com.geniusxiaoyu.utils;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.InputStream;  
  5.   
  6. public class StreamTool {  
  7.   
  8.     /** 
  9.      * 从输入流中获取数据 
  10.      * @param is 
  11.      * @return 
  12.      */  
  13.     public static byte[] readInputStream(InputStream is) throws Exception{  
  14.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  15.         byte[] buf = new byte[1024];  
  16.         int len = 0;  
  17.         while((len = is.read(buf)) != -1){  
  18.             baos.write(buf, 0, len);  
  19.         }  
  20.         baos.close();  
  21.         return baos.toByteArray();  
  22.     }  
  23. }  

AndroidManifest.xml

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="com.geniusxiaoyu.url"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:name=".URLActivity"  
  8.                   android:label="@string/app_name">  
  9.             <intent-filter>  
  10.                 <action android:name="android.intent.action.MAIN" />  
  11.                 <category android:name="android.intent.category.LAUNCHER" />  
  12.             </intent-filter>  
  13.         </activity>  
  14.   
  15.     </application>  
  16.     <uses-sdk android:minSdkVersion="8" />  
  17.     <!-- 访问internet权限 -->  
  18.     <uses-permission android:name="android.permission.INTERNET"/>  
  19.       
  20. </manifest>   
0 0
原创粉丝点击