package com.wuyou.htmlcodeviewer;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.ActionBarActivity;import android.text.TextUtils;import android.view.View;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;public class MainActivity extends ActionBarActivity { private static final int ERROR = 0; private static final int CHANGE_TEXT = 1; private EditText editText; private TextView textView; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == CHANGE_TEXT) { textView.setText((String) msg.obj); } else if (msg.what == ERROR) { Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText) findViewById(R.id.et); textView = (TextView) findViewById(R.id.tv); } public void click(View view) { new Thread(new Runnable() { @Override public void run() { try { String path = editText.getText().toString().trim(); if (TextUtils.isEmpty(path)) { Message message = new Message(); message.what = ERROR; message.obj = "地址不能为空!"; handler.sendMessage(message); } else { URL url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0"); httpURLConnection.setConnectTimeout(5000);//设置连接服务器如果没有在5秒钟运行则抛出错误 if (httpURLConnection.getResponseCode() == 200) { InputStream is = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line = null; StringBuilder sb = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { sb.append(line); } Message message = new Message(); message.what = CHANGE_TEXT; message.obj = sb.toString(); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); Message message = new Message(); message.what = ERROR; message.obj = "出错了!"; handler.sendMessage(message); } } }).start(); }}
<uses-permission android:name="android.permission.INTERNET"/>