当前位置:Gxlcms > html代码 > 如何用网络获取Html代码?网络获取Html代码原理

如何用网络获取Html代码?网络获取Html代码原理

时间:2021-07-01 10:21:17 帮助过:38人阅读

如何用网络获取Html代码?下面小编带来一篇网络获取Html代码原理,仅供参考作用

  1. package cn.captain.html;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.InputStream;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. public class htmlRequest {
  7. /**
  8. * @param args
  9. * @throws MalformedURLException
  10. */
  11. public static void main(String[] args) throws Exception
  12. {
  13. URL url = new URL("http://www.baidu.com/");
  14. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  15. conn.setRequestMethod("GET");
  16. conn.setConnectTimeout(5 * 1000);
  17. InputStream inStream = conn.getInputStream();//通过输入流获取html数据
  18. byte[] data = readInputStream(inStream);//得到html的二进制数据
  19. String html = new String(data);
  20. System.out.println(html);
  21. }
  22. public static byte[] readInputStream(InputStream instream) throws Exception
  23. {
  24. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  25. byte[] buffer = new byte[1204];
  26. int len = 0;
  27. while ((len = instream.read(buffer)) != -1)
  28. {
  29. outStream.write(buffer,0,len);
  30. }
  31. instream.close();
  32. return outStream.toByteArray();
  33. }
  34. }

以上就是如何用网络获取Html代码?网络获取Html代码原理的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行