【Android開發】網絡通信之網頁源碼查看器
今天學習了安卓開發中有關網絡通信相關的東西。
根據教學視頻,我按照步驟寫了一個“網頁源碼查看器”。通過寫這個東西,我學會了使用URL和 HttpURLConnection取得與網站的鏈接
部分鏈接代碼:
/* * 獲取網頁html源代碼: * path 網頁路徑 * */ public static String getHtml(String path) throws Exception{ //將path包裝成一個URL對象 URL url=new URL(path); //取得鏈接對象(基於HTTP協議鏈接對象) HttpURLConnection conn=(HttpURLConnection) url.openConnection(); //設置超時時間 conn.setConnectTimeout(5000); //設置請求方式 conn.setRequestMethod("GET"); //判斷請求是否成功(看一下getResponseCode) if(conn.getResponseCode()==200){ InputStream instream=conn.getInputStream(); //流的工具類,專門從流中讀取數據(返回的是二進製數據) byte[] data= streamTool.read(instream); String html= new String(data,"UTF-8"); return html; } return null; }
上麵的代碼中有一個streamTool.的工具類,也是要自己去寫的,通過寫這個類,學會了java中IO流的部分應用。
下麵代碼中的instream是上麵傳進去的輸入流對象
部分代碼:
/* * 讀取流中的數據 * */ public static byte[] read(InputStream instream) throws Exception{ ByteArrayOutputStream outStream=new ByteArrayOutputStream(); //定義一個字節數組 byte[] buffer=new byte[1024]; //讀滿數組,就會返回(返回的是int型,代表讀取的數組長度) //當返回值為-1時說明已經讀完 int len=0; while((len = instream.read(buffer)) !=-1){ //buffer有多少數據就讀多少 outStream.write(buffer, 0, len); } instream.close(); return outStream.toByteArray(); }
在主界麵得到html信息並顯示
private EditText pathText; private TextView codeView; @Override protected 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 OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String path=pathText.getText().toString(); String html; try { html = PageSevice.getHtml(path); codeView.setText(html); } catch (Exception e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), R.string.error, 1).show(); } } }); }
效果圖:
轉載請注明原址:https://blog.csdn.net/acmman
讀取圖片也不難,顯示界麵稍加改造即可(當然相應的類(如ImageSevice)也要寫):
Image View imageView =(Image View) findviewbyId(R.id.imageview); String path=pathText.getText().toString(); byte[] data=ImageSevice.getImage(path); Bitmap bitmap=BitmapFactory.decodeByteArray(data,0,data.length); imageView.setImageBitmap(bitmap);//顯示圖片
最後更新:2017-04-03 05:39:58