【获取网页源码】
1 package cn.itcast.htmlviewer; 2 3 import cn.itcast.service.PageService; 4 import android.app.Activity; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.Button; 8 import android.widget.EditText; 9 import android.widget.TextView; 10 import android.widget.Toast; 11 12 public class MainActivity extends Activity { 13 private EditText pathText; 14 private TextView codeView; 15 16 @Override 17 public void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.main); 20 21 pathText = (EditText) this.findViewById(R.id.pagepath); 22 codeView = (TextView) this.findViewById(R.id.codeView); 23 Button button = (Button) this.findViewById(R.id.button); 24 button.setOnClickListener(new ButtonClickListener()); 25 } 26 27 private final class ButtonClickListener implements View.OnClickListener{ 28 29 public void onClick(View v) { 30 String path = pathText.getText().toString(); 31 try{ 32 String html = PageService.getHtml(path); 33 codeView.setText(html); 34 }catch (Exception e) { 35 e.printStackTrace(); 36 Toast.makeText(getApplicationContext(), R.string.error, 1).show(); 37 } 38 } 39 40 } 41 }
1 package cn.itcast.service; 2 3 import java.io.InputStream; 4 import java.net.HttpURLConnection; 5 import java.net.URL; 6 7 import cn.itcast.utils.StreamTool; 8 9 public class PageService { 10 /** 11 * 获取网页HTML源代码 12 * @param path 网页路径 13 * @return 14 */ 15 public static String getHtml(String path) throws Exception{ 16 URL url = new URL(path); 17 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 18 conn.setConnectTimeout(5000); 19 conn.setRequestMethod("GET"); 20 if(conn.getResponseCode() == 200){ 21 InputStream inStream = conn.getInputStream(); 22 byte[] data = StreamTool.read(inStream); 23 String html = new String(data, "UTF-8"); 24 return html; 25 } 26 return null; 27 } 28 29 }
1 package cn.itcast.utils; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.InputStream; 5 6 public class StreamTool { 7 /** 8 * 读取流中的数据 9 * @param inStream 10 * @return 11 * @throws Exception 12 */ 13 public static byte[] read(InputStream inStream) throws Exception{ 14 ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 15 byte[] buffer = new byte[1024]; 16 int len = 0; 17 while( (len = inStream.read(buffer)) != -1){ 18 outStream.write(buffer, 0, len); 19 } 20 inStream.close(); 21 return outStream.toByteArray(); 22 } 23 24 }