Android 开发工具类 24_getHtml
获取网页(JSP)源码
1 import java.io.InputStream; 2 import java.net.HttpURLConnection; 3 import java.net.URL; 4 5 import com.wangjialin.internet.utils.StreamTool; 6 7 public class HtmlService { 8 /** 9 * 获取网页源码 10 * @param path 网页路径 11 * @return 12 */ 13 public static String getHtml(String path) throws Exception { 14 15 HttpURLConnection conn = (HttpURLConnection)new URL(path).openConnection(); 16 conn.setConnectTimeout(5000); 17 conn.setRequestMethod("GET"); 18 19 if(conn.getResponseCode() == 200){ 20 21 InputStream inStream = conn.getInputStream(); 22 byte[] data = StreamTool.read(inStream); 23 return new String(data); 24 } 25 return null; 26 } 27 }
StreamTool.java
1 import java.io.ByteArrayOutputStream; 2 import java.io.InputStream; 3 4 public class StreamTool { 5 6 /** 7 * 从流中读取数据 8 * @param inStream 9 * @return 10 */ 11 public static byte[] read(InputStream inStream) throws Exception{ 12 13 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 14 byte[] buffer = new byte[1024]; 15 int len = 0; 16 17 while((len = inStream.read(buffer)) != -1){ 18 outputStream.write(buffer, 0, len); 19 } 20 inStream.close(); 21 return outputStream.toByteArray(); 22 } 23 }
显示网页源码 pathText = "http://192.168.1.103:8080/ServerForWebCodeViewer/wangjialin.jsp"
1 public void showhtml(View v) { 2 3 path = pathText.getText().toString(); 4 try { 5 new Thread(new Runnable(){ 6 7 @Override 8 public void run() { 9 // TODO Auto-generated method stub 10 try { 11 html = HtmlService.getHtml(path); 12 } catch (Exception e) { 13 // TODO Auto-generated catch block 14 e.printStackTrace(); 15 } 16 } 17 }).start(); 18 19 textView.setText(html); 20 } catch (Exception e) { 21 e.printStackTrace(); 22 Toast.makeText(getApplicationContext(), R.string.error, Toast.LENGTH_LONG).show(); 23 } 24 25 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。