这篇博文适用于刚刚接触移动开发利用网络连接加载数据的小伙伴们,
分废话不多说,直接贴代码。
MainActivity.class
package com.example.htmlcode;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
public class MainActivity extends Activity implements OnClickListener {
private EditText edt_path;
private Button btn_ok;
private TextView tv_html;
private static final int success=0;
private static final int Error=1;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what){
case success:
tv_html.setText((String) msg.obj);
break;
case Error:
Toast.makeText(MainActivity.this, "访问失败", 0).show();
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_path=(EditText) findViewById(R.id.edt_URL);
btn_ok=(Button) findViewById(R.id.btn_ok);
tv_html=(TextView) findViewById(R.id.tv_html);
btn_ok.setOnClickListener(this);
}
@Override
public void onClick(View v) {
final String path=edt_path.getText().toString();
//访问网络时new一个子线程
new Thread(new Runnable() {
@Override
public void run() {
//请求网络
String html= getHtmlFromNet(path);
if(!TextUtils.isEmpty(html)){
//更新TextView显示
Message msg=new Message();
msg.what=success;
msg.obj=html;
handler.sendMessage(msg);
}else{
//更新TextView显示
Message msg=new Message();
msg.what=Error;
msg.obj=html;
handler.sendMessage(msg);
}
}
}).start();
}
/*
* 根据给定的path访问网络,去抓取html代码
* @param path
* @return html
* */
public String getHtmlFromNet(String path) {
try {
URL murl=new URL(path);//创建一个URL对象
HttpURLConnection conn=(HttpURLConnection) murl.openConnection();//得到URL连接对象
conn.setRequestMethod("GET");//设置请求方式
conn.setConnectTimeout(10000);//设置连接网络超时时间
conn.setReadTimeout(5000);//设置读取超时时间
conn.connect();//开始连接
int responseCode=conn.getResponseCode();//得到服务器响应码
if(responseCode == 200){
//访问成功
InputStream is=conn.getInputStream();//得到服务器返回的数据流
String html=getStringFromInputStream(is);
return html;
}else{
//访问失败
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/*
* 根据流返回字符串信息
* @param is
* @return html
* */
private String getStringFromInputStream(InputStream is) throws IOException{
ByteArrayOutputStream baos=new ByteArrayOutputStream();//定义一个缓存流
byte[] buffer=new byte[1024];//定义一个字节数组,去读取is
int len=-1;
while((len = is.read(buffer)) != -1) {//将字节写入缓存
baos.write(buffer, 0, len);
}
is.close();//关闭输入流
String html = baos.toString();
baos.close();//关闭缓存流
return html;
}
}
布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="网页路径" />
<EditText
android:id="@+id/edt_URL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="http://192.168.1.106:8080/server_test/index.jsp"
/>
<Button
android:id="@+id/btn_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查看"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/tv_html"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
需要注意的是:在访问自己编写的网页时,一般用http://locallhost:8080/工程名/文件名.jsp
在计算机中 locallhost表示本机 ,再用android模拟器或真机测试时也是代表访问本机,所以用localhost是访问不到的。
在用模拟器时可以使用10.0.2.2(代表计算机的签名)进行访问。
在用真机测试时需要保证机器和计算机在同一局域网下,然后用本机的IP地址进行访问
在命令代码行中输入ipconfig 然后找到ipv4地址就是你本机的ip了,在每次关闭开启计算机后IP地址会发生改变。
还有不要忘了添加权限啊
<uses-permission android:name="android.permission.INTERNET" />
感觉我好啰嗦呀 ,哈哈
![大笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/laugh.gif)