Android获取HTML数据_安卓从Internet获取HTML例子
程序员文章站
2022-03-01 15:14:14
...
从网络中获取一张 HTML 页面的内容、相信很多哥们会有这个需求、同样
今天我也遇到了这个问题、在网络上查找了很多资料、最后还是研究出来了
那下面我把我的研究成果和大家分享一下、希望对一些哥们有帮助、话不多说
下面是封装的一个用于获取 HTML 页面的一个类、哥们只需要在自己的 Activity 里面调用即可
package com.dwtedx.service; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import com.dwtedx.utils.StreamTool; public class HtmlService { public static String getHtml(String path) throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url .openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); //通过输入流获取html数据 InputStream inStream = conn.getInputStream(); //得到html的二进制数据 byte[] data = readInputStream(inStream); String html = new String(data, "gb2312"); return html; } 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(); } }下面我把我在 Activity 里面的调用方法贴出来
package com.dwtedx.html; import com.dwtedx.service.HtmlService; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { //Called when the activity is first created. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView textView = (TextView)this .findViewById(R.id.textView); try { textView.setText(HtmlService .getHtml("http://www.dwtedx.com")); } catch (Exception e) { Log.e("MainActivity", e.toString()); Toast.makeText(MainActivity.this, "网络连接失败", 1).show(); } } }