1.直接上效果圖
2.代碼
主要就是工具類HtmlService.java:
import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * 獲取HTML數據 * * @author David * */ public class HtmlService { public static String getHtml(String path) throws Exception { // 通過網絡地址創建URL對象 URL url = new URL(path); // 根據URL // 打開連接,URL.openConnection函數會根據URL的類型,返回不同的URLConnection子類的對象,這里URL是一個http,因此實際返回的是HttpURLConnection HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 設定URL的請求類別,有POST、GET 兩類 conn.setRequestMethod("GET"); //設置從主機讀取數據超時(單位:毫秒) conn.setConnectTimeout(5000); //設置連接主機超時(單位:毫秒) conn.setReadTimeout(5000); // 通過打開的連接讀取的輸入流,獲取html數據 InputStream inStream = conn.getInputStream(); // 得到html的二進制數據 byte[] data = readInputStream(inStream); // 是用指定的字符集解碼指定的字節數組構造一個新的字符串 String html = new String(data, "utf-8"); return html; } /** * 讀取輸入流,得到html的二進制數據 * * @param inStream * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); } }
MainActivity.java 修改如下:
public class MainActivity extends Activity { private String path = "http://www.cnblogs.com/yc-755909659/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = (TextView)this.findViewById(R.id.textView); try { String htmlContent = HtmlService.getHtml(path); textView.setText(htmlContent); } catch (Exception e) { textView.setText("程序出現異常:"+e.toString()); } } }
activity_main.xml 很簡單,還是放上來吧
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </ScrollView>
最后,記得添加網絡訪問權限哦
<uses-permission android:name="android.permission.INTERNET"/>