1:androidmanifest.xml的内容
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itcast.htmlview"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
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" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
2:布局文件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"
>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/html"
/>
</ScrollView>
</LinearLayout>
3:MainActivity的内容
package com.itcast.htmlview;
import java.io.IOException;
import com.itcast.service.HtmlService;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView)findViewById(R.id.html);
String path = "http://www.163.com/";
try {
String htmlContent = HtmlService.getHtmlContent(path);
tv.setText(htmlContent);
} catch (IOException e) {
Log.e(TAG, e.toString());
Toast.makeText(MainActivity.this, "连接超时", Toast.LENGTH_LONG);
}
}
}
4:HtmlService的内容
package com.itcast.service;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.itcast.utils.StreamTool;
public class HtmlService {
public static String getHtmlContent(String path) throws IOException {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
InputStream inputStream = conn.getInputStream(); //通过输入流获得网站数据
byte[] getData = StreamTool.readInputStream(inputStream); //获得网站的二进制数据
String data = new String(getData, "gb2312");
return data;
}
}
5:StreamTool类
package com.itcast.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class StreamTool {
/*
* 从数据流中获得数据
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}
6:程序界面与效果图
当下拉时右边会显示一个下拉的列表