Android通過(guò)訪問(wèn)網(wǎng)頁(yè)查看網(wǎng)頁(yè)源碼
成都創(chuàng)新互聯(lián)公司為您提適合企業(yè)的網(wǎng)站設(shè)計(jì)?讓您的網(wǎng)站在搜索引擎具有高度排名,讓您的網(wǎng)站具備超強(qiáng)的網(wǎng)絡(luò)競(jìng)爭(zhēng)力!結(jié)合企業(yè)自身,進(jìn)行網(wǎng)站設(shè)計(jì)及把握,最后結(jié)合企業(yè)文化和具體宗旨等,才能創(chuàng)作出一份性化解決方案。從網(wǎng)站策劃到成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè), 我們的網(wǎng)頁(yè)設(shè)計(jì)師為您提供的解決方案。
1.添加網(wǎng)絡(luò)權(quán)限
2.獲取網(wǎng)絡(luò)中網(wǎng)頁(yè)的數(shù)據(jù)
/** * 獲取網(wǎng)頁(yè)HTML源代碼 * @param path 網(wǎng)頁(yè)路徑 */ 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)頁(yè)源碼的控制
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)頁(yè)路徑 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); } } } }
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!