1.主MainActivity 类代码如下:
public class MainActivity extends Activity {
private EditText pathText;
private TextView codeView;
private Button button;
private String html;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
codeView.setText(html);
}
};
Runnable runnable = new Runnable() {
@Override
public void run() {
String path = pathText.getText().toString();
try {
html = HtmlTool.getHtml(path);
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(MainActivity.this, "获取图片失败", 1).show();
e.printStackTrace();
}
Message msg = new Message();
handler.sendMessage(msg);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pathText = (EditText) findViewById(R.id.pagepath);
codeView = (TextView) findViewById(R.id.codeView);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread(runnable).start();
}
});
}
}
2.HtmlTool类代码:
public class HtmlTool {
public static String getHtml(String path) throws Exception {
// TODO Auto-generated method stub
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
if (connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
byte data[] = read(inputStream);
String html = new String(data, "UTF-8");
return html;
}
return null;
}
private static byte[] read(InputStream inputStream) throws IOException {
// TODO Auto-generated method stub
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
int len = 0;
byte buffer[] = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
arrayOutputStream.write(buffer, 0, len);
}
// arrayOutputStream.close();
inputStream.close();
return arrayOutputStream.toByteArray();
}
}
3.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/pagepath" />
<EditText
android:id="@+id/pagepath"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="http://blog.youkuaiyun.com/evahuangchen/article/details/48292747" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/codeView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
4.清单文件里加权限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
5.运行结果: