public class MainActivity extends Activity implements OnClickListener {
private EditText pathText;
private TextView codeView;
String html = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.button);
pathText = (EditText) this.findViewById(R.id.pagepath);
codeView = (TextView) this.findViewById(R.id.codeView);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button:
String path = pathText.getText().toString();
readpage(path);
break;
default:
break;
}
}
protected void readpage(final String path) {
// TODO Auto-generated method stub
new Thread() {
@Override
public void run() {
// 把网络访问的代码放在这里
try {
html = PageService.getHtml(path);
handler.sendEmptyMessage(0);
} catch (Exception e) {
e.printStackTrace();
// Toast.makeText(getApplicationContext(), R.string.err,
// 1).show();
}
}
}.start();
}
// 定义Handler对象
private Handler handler = new Handler() {
@Override
// 当有消息发送出来的时候就执行Handler的这个方法
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 处理UI
codeView.setText(html);
}
};
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/pagepath" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="http://3.shyule1.sinaapp.com/index.html"
android:id="@+id/pagepath"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:id="@+id/button"
/>
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/codeView"
/>
</ScrollView>
</LinearLayout>
public class PageService {
//获取网页html源代码
public static String getHtml(String path) throws Exception {
// TODO Auto-generated method stub
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){
InputStream inStream=conn.getInputStream();
byte[] data=StreamTool.read(inStream);
String html=new String(data,"UTF-8");
return html;
}
return null;
}
}
public class StreamTool {
//读取流中的数据
public static byte[] read(InputStream instream) throws Exception {
// TODO Auto-generated method stub
ByteArrayOutputStream outStream=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int d=0;
while((d=instream.read(buffer))!=-1){
outStream.write(buffer, 0, d);
}
instream.close();
return outStream.toByteArray();
}
}