Android通過訪問網(wǎng)頁查看網(wǎng)頁源碼實例詳解
更新時間:2017年06月02日 17:01:00 投稿:lqh
這篇文章主要介紹了Android通過訪問網(wǎng)頁查看網(wǎng)頁源碼的相關(guān)資料,需要的朋友可以參考下
Android通過訪問網(wǎng)頁查看網(wǎng)頁源碼
1.添加網(wǎng)絡(luò)權(quán)限
<!--訪問網(wǎng)絡(luò)的權(quán)限--> <uses-permission android:name="android.permission.INTERNET"/>
2.獲取網(wǎng)絡(luò)中網(wǎng)頁的數(shù)據(jù)
/** * 獲取網(wǎng)頁HTML源代碼 * @param path 網(wǎng)頁路徑 */ public static String getHtml(String path) throws Exception { URL url=new URL(path); HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode()==200){ InputStream inStream=conn.getInputStream(); byte[] data=read(inStream); String html=new String(data,"UTF-8"); return html; } return null; } /** * 讀取流中的數(shù)據(jù) */ public static byte[] read(InputStream inputStream) throws IOException { ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); byte[] b=new byte[1024]; int len=0; while((len=inputStream.read(b))!=-1){ outputStream.write(b); } inputStream.close(); return outputStream.toByteArray(); }
3.處理查看網(wǎng)頁源碼的控制
public class HtmlViewActivity extends Activity { private EditText pathText; private TextView codeView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); pathText=(EditText) findViewById(R.id.pagepath);//網(wǎng)頁路徑 codeView=(TextView)findViewById(R.id.codeView);//顯示獲得的源碼 Button button=(Button) findViewById(R.id.button);//查看按鈕 button.setOnClickListener(new ButtonClickListener());//按鈕事件 } /** * 查看按鈕處理事件 */ private final class ButtonClickListener implements View.OnClickListener{ @Override public void onClick(View v) { String path=pathText.getText().toString(); try { String html=PageService.getHtml(path); codeView.setText(html); } catch (Exception e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), R.string.error, 1); } } } }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Android實現(xiàn)調(diào)用系統(tǒng)圖庫與相機設(shè)置頭像并保存在本地及服務(wù)器
這篇文章主要介紹了Android實現(xiàn)調(diào)用系統(tǒng)圖庫與相機設(shè)置頭像并保存在本地及服務(wù)器 ,需要的朋友可以參考下2017-03-03Android 類似UC瀏覽器的效果:向上滑動地址欄隱藏功能
這篇文章主要介紹了Android 類似UC瀏覽器的效果:向上滑動地址欄隱藏功能,需要的朋友可以參考下2017-12-12Android Handler中的休眠喚醒實現(xiàn)詳解
這篇文章主要為大家介紹了Android Handler中的休眠喚醒實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01