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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/urlpath"
/>
<EditText
android:id="@+id/urlpath"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="http://www.baidu.com/img/baidu_sylogo1.gif"
/>
<Button
android:id="@+id/imagebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/imagebutton"
/>
<Button
android:id="@+id/htmlbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/htmlbutton"
/>
<ImageView
android:id="@+id/showimage"
android:layout_width="fill_parent"
android:layout_height="300dip"
android:scaleType="fitCenter"
/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="@+id/showhtml"
android:minLines="5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
数据文件:values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, URLActivity!</string>
<string name="app_name">URL测试</string>
<string name="urlpath">请输入图片网络地址</string>
<string name="imagebutton">显示图片</string>
<string name="htmlbutton">显示文本</string>
<string name="error">获取图片失败</string>
</resources>
Activity,URLActivity.java
package com.geniusxiaoyu.url;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.geniusxiaoyu.service.URLService;
public class URLActivity extends Activity {
private static final String TAG = "URLActivity";
private EditText pathText;
private EditText htmlText;
private ImageView imageView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pathText = (EditText)findViewById(R.id.urlpath);
htmlText = (EditText)findViewById(R.id.showhtml);
imageView = (ImageView)findViewById(R.id.showimage);
Button imagebutton = (Button)findViewById(R.id.imagebutton);
//添加点击事件
imagebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String path = pathText.getText().toString();
//显示与隐藏组件
htmlText.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
try {
byte[] data = URLService.getBitData(path);
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);//生成位图
imageView.setImageBitmap(bitmap);//显示图片
} catch (Exception e) {
Toast.makeText(URLActivity.this, R.string.error, 1).show();
Log.e(TAG, e.toString());
}
}
});
Button htmlbutton = (Button)findViewById(R.id.htmlbutton);
//添加点击事件
htmlbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String path = pathText.getText().toString();
//显示与隐藏组件
imageView.setVisibility(View.GONE);
htmlText.setVisibility(View.VISIBLE);
try {
byte[] data = URLService.getBitData(path);
String html = new String(data);
//显示文本
htmlText.setText(html);
} catch (Exception e) {
Toast.makeText(URLActivity.this, R.string.error, 1).show();
Log.e(TAG, e.toString());
}
}
});
}
}
URLService.java
package com.geniusxiaoyu.service;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.geniusxiaoyu.utils.StreamTool;
public class URLService {
/**
* 获取图片数据
* @param path
* @return
* @throws Exception
*/
public static byte[] getBitData(String path) throws Exception{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(1000 * 5);
conn.setRequestMethod("GET");
InputStream is = conn.getInputStream();
return StreamTool.readInputStream(is);
}
}
StreamTool.java
package com.geniusxiaoyu.utils;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTool {
/**
* 从输入流中获取数据
* @param is
* @return
*/
public static byte[] readInputStream(InputStream is) throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = is.read(buf)) != -1){
baos.write(buf, 0, len);
}
baos.close();
return baos.toByteArray();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.geniusxiaoyu.url"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".URLActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
<!-- 访问internet权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>