Android WebページにアクセスしてWebソースを表示

1957 ワード

1.ネットワーク権限の追加
<!--       -->
<uses-permission android:name="android.permission.INTERNET"/>

2.ネットワーク内のWebページのデータを取得する
/**
	 *     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.Webソースの表示制御の処理
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);
			}
		}
	}
}