Android网页源代码查看器
布局文件
<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="wrap_content"
android:layout_height="wrap_content"
android:text="输入代码获取路径"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/path"
android:text="http://172.16.121.10:8080/struts27/"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="确定"
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>
MainActivity
public class MainActivity extends Activity {
private EditText pathView;
private TextView codeView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
codeView = (TextView) this.findViewById(R.id.codeView);
pathView = (EditText) this.findViewById(R.id.path);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new button_OnClickListener());
}
private class button_OnClickListener implements View.OnClickListener{
@Override
public void onClick(View v) {
String path = pathView.getText().toString();
try {
String html = HtmlService.getHtmlCode(path); //获取Html数据
codeView.setText(html);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "获取失败", 1);
e.printStackTrace();
}
}
}
}
//获取代码业务类
public static StringgetHtmlCode(Stringpath) throws Exception {
URLurl = new URL(path);
HttpURLConnectionconn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()== 200){
InputStreamin = conn.getInputStream();
byte[] code = StreamTool.read(in);
return new String(code);
}
return null;
}
//读取二进制数据工具类
public static byte[] read(InputStream in) throws Exception {
ByteArrayOutputStreamout = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0 ;
while((len =in.read(buffer)) != -1){
out.write(buffer,0, len);
}
in.close();
return out.toByteArray();
}