如何用网络获取Html代码?下面小编带来一篇网络获取Html代码原理,仅供参考作用
package cn.captain.html;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class htmlRequest {
/**
* @param args
* @throws MalformedURLException
*/
public static void main(String[] args) throws Exception
{
URL url = new URL("http://www.baidu.com/");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();//通过输入流获取html数据
byte[] data = readInputStream(inStream);//得到html的二进制数据
String html = new String(data);
System.out.println(html);
}
public static byte[] readInputStream(InputStream instream) throws Exception
{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1204];
int len = 0;
while ((len = instream.read(buffer)) != -1)
{
outStream.write(buffer,0,len);
}
instream.close();
return outStream.toByteArray();
}
}以上就是如何用网络获取Html代码?网络获取Html代码原理的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号