国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android通過訪問網頁查看網頁源碼實例詳解

2019-10-23 18:27:12
字體:
來源:轉載
供稿:網友

Android通過訪問網頁查看網頁源碼

1.添加網絡權限

<!--訪問網絡的權限--> <uses-permission android:name="android.permission.INTERNET"/> 

2.獲取網絡中網頁的數據

/**    * 獲取網頁HTML源代碼    * @param path 網頁路徑    */   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;   }    /**    * 讀取流中的數據    */   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.處理查看網頁源碼的控制

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);//網頁路徑     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);       }     }   } } 

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 科技| 曲周县| 上林县| 灵武市| 鹤山市| 鄂尔多斯市| 灌南县| 尚义县| 措勤县| 休宁县| 桐梓县| 上杭县| 威宁| 葫芦岛市| 潜江市| 扶沟县| 新安县| 高唐县| 楚雄市| 蒙阴县| 都昌县| 巴彦淖尔市| 汝阳县| 达拉特旗| 南皮县| 昔阳县| 花莲市| 青海省| 怀远县| 灵山县| 饶阳县| 淮滨县| 甘德县| 定兴县| 寿宁县| 饶阳县| 盱眙县| 驻马店市| 景谷| 江都市| 小金县|