编写如下项目:

2编写Android清单文件
package=“com.itheima28.htmldemo”
android:versionCode=“1”
android:versionName=“1.0” >
android:minSdkVersion=“8”
android:targetSdkVersion=“19” />
android:allowBackup=“true”
android:icon=“@drawable/ic_launcher”
android:label=“@string/app_name”
android:theme=“@style/AppTheme” >
android:name=“com.itheima28.htmldemo.MainActivity”
android:label=“@string/app_name” >
3编写布局文件activity_main.xml
xmlns:tools=“http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:orientation=“vertical”
tools:context=“.MainActivity” >
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:orientation=“horizontal”>
android:id=“@+id/et_url”
android:layout_width=“0dip”
android:text=“http://www.baidu.com”
android:layout_height=“wrap_content”
android:singleLine=“true”
android:layout_weight=“1”/>
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:onClick=“getHtml”
android:text=“GO”/>
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”>
android:id=“@+id/tv_html”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”/>
4编写Activity的类MainActivity如下:
packagecom.itheima28.htmldemo;
importjava.io.ByteArrayOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URL;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.text.TextUtils;
importandroid.util.Log;
importandroid.view.View;
importandroid.widget.EditText;
importandroid.widget.TextView;
importandroid.widget.Toast;
publicclassMainActivityextendsActivity {
privatestaticfinalStringTAG=“MainActivity”;
privatestaticfinalintSUCCESS= 0;
protectedstaticfinalintERROR= 1;
privateEditTextetUrl;
privateTextViewtvHtml;
privateHandlerhandler=newHandler() {
@Override
publicvoidhandleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what) {
caseSUCCESS:
tvHtml.setText((String) msg.obj);
break;
caseERROR:
Toast.makeText(MainActivity.this,“访问失败“, 0).show();
break;
default:
break;
}
}
};
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUrl= (EditText) findViewById(R.id.et_url);
tvHtml= (TextView) findViewById(R.id.tv_html);
}
publicvoidgetHtml(View v) {
finalString url =etUrl.getText().toString();
newThread(newRunnable() {
@Override
publicvoidrun() {
//请求网络
String html = getHtmlFromInternet(url);
if(!TextUtils.isEmpty(html)) {
//更新textview的显示了
Message msg =newMessage();
msg.what=SUCCESS;
msg.obj= html;
handler.sendMessage(msg);
}else{
Message msg =newMessage();
msg.what=ERROR;
handler.sendMessage(msg);
}
}
}).start();
}
/**
*根据给定的url访问网络,抓去html代码
*@paramurl
*@return
*/
protectedString getHtmlFromInternet(String url) {
try{
URL mURL =newURL(url);
HttpURLConnection conn = (HttpURLConnection) mURL.openConnection();
conn.setRequestMethod(“GET”);
conn.setConnectTimeout(10000);
conn.setReadTimeout(5000);
//conn.connect();
intresponseCode = conn.getResponseCode();
if(responseCode == 200) {
InputStream is = conn.getInputStream();
String html = getStringFromInputStream(is);
returnhtml;
}else{
Log.i(TAG,“访问失败: “+ responseCode);
}
}catch(Exception e) {
e.printStackTrace();
}
returnnull;
}
/**
*根据流返回一个字符串信息
*@paramis
*@return
*@throwsIOException
*/
privateString getStringFromInputStream(InputStream is)throwsIOException {
ByteArrayOutputStream baos =newByteArrayOutputStream();
byte[] buffer =newbyte[1024];
intlen = -1;
while((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
is.close();
String html = baos.toString();//把流中的数据转换成字符串,采用的编码是: utf-8
String charset =“utf-8”;
if(html.contains(“gbk”) || html.contains(“gb2312”)
|| html.contains(“GBK”) || html.contains(“GB2312”)) {//如果包含gbk, gb2312编码,就采用gbk编码进行对字符串编码
charset =“gbk”;
}
html =newString(baos.toByteArray(), charset);//对原有的字节数组进行使用处理后的编码名称进行编码
baos.close();
returnhtml;
}
}
该博客展示了如何在Android中实现网络请求以获取HTML内容,并在主线程中更新UI。通过创建AndroidManifest.xml文件设置应用信息,布局activity_main.xml定义用户界面,以及MainActivity.java处理网络请求和UI交互,博主详细解释了网络请求过程和错误处理机制。
2813

被折叠的 条评论
为什么被折叠?



