java 之URLConnection学习

URLConnection获取本地网页的源码:

package cn.itcast.p99.ie_server.demo;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class URLDemo {

	public static void main(String[] args) throws IOException {
		String urlString = "http://localhost:8080/%E4%BA%AC%E4%B8%9C%E7%BD%91%E9%A1%B5/index.html";
		URL url = new URL(urlString);
		InputStream inputStream = url.openStream();
		
		URLConnection connection = url.openConnection();
		
		System.out.println(connection);
		
		System.out.println("-----------------------------------------------------------------------------------------");
		
		String valueString = connection.getHeaderField("Content-Type");
		System.out.println(valueString);
		System.out.println("-----------------------------------------------------------------------------------------");

		
		byte[] buf = new byte[1024];
		int len = inputStream.read(buf);
		
		String  string = new String(buf, 0, len);
		System.out.println(string);
		
		inputStream.close();
		
	}

}

控制台打印:

sun.net.www.protocol.http.HttpURLConnection:http://localhost:8080/%E4%BA%AC%E4%B8%9C%E7%BD%91%E9%A1%B5/index.html
-----------------------------------------------------------------------------------------
text/html
-----------------------------------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="css/base.css">
    <link rel="stylesheet" href="css/index.css">
    <link rel="stylesheet icon" href="favicon.ico">
    <script type="text/javascript">
        window.onload = function () {
            var login = document.getElementById("login");
            var mask = document.getElementById("mask");
            var  box = document.getElementById("box");
            login.onclick = function () {
                mask.style.display = "block";
                box.style.display = "block";

            }
            var close_all = document.getElementById("close_all");
            close_all.onclick = function () {
                mask.style.display = "none";
                box.style.display = "none";
            }
        }

    </script>

</head>
<body>

<!--京东头部导航开始-->
<div id="mask">

</div>
<div id="box">
    <span id="close_all">x</span>

这个url是我本地写的一个简易京东网页demo。

猜你喜欢

转载自blog.csdn.net/weixin_40200876/article/details/87880950