qq_34536908
qq_34536908
采纳率50%
2016-12-05 05:56 阅读 9.0k
已采纳

java 异常java.net.UnknownHostException

package app21;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketTest1 {

public static void main(String[] args) {
    String host = "www.baidu.com";
    String protocol = "https";
    try {
        Socket socket = new Socket(protocol + "://" + host, 80);
        OutputStream os = socket.getOutputStream();
        boolean autoflush = true;
        PrintWriter out = new PrintWriter(os, autoflush);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
        // 将一个HTTP请求发送到Web服务器
        out.println("GET / HTTP/1.1");
        out.println("Host: " + host + ":80");
        out.println("Connection: Close");
        out.println();

        // 读取响应信息
        boolean loop = true;
        StringBuilder sb = new StringBuilder(8096);
        while (loop) {
            if (in.ready()) {
                int i = 0;
                while (i != -1) {
                    i = in.read();
                    sb.append((char) i);
                }
                loop = false;
            }
        }

        // 将响应信息显示到out控制台
        System.out.println(sb.toString());
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

异常信息:
java.net.UnknownHostException: https://www.baidu.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.(Socket.java:434)
at java.net.Socket.(Socket.java:211)
at app21.SocketTest1.main(SocketTest1.java:16)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    huixinjinkongxin 糖果给你 2016-12-05 06:06

    改成这个
    Socket socket = new Socket(host, 80);

    点赞 评论 复制链接分享
  • xubo_ob 海_贼-王 2016-12-05 06:08

    哥们,建议你在cmd中ping一下,看你的本机是否能够连接到百度 。。 估计你没有联网 。

    点赞 1 评论 复制链接分享
  • qq_32218415 何三 2019-10-15 15:54

    不要https://

    Socket socket = new Socket("www.baidu.com", 80);

    点赞 评论 复制链接分享

相关推荐