qq_34536908
2016-12-05 05:56
采纳率: 50%
浏览 9.4k
已采纳

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条回答 默认 最新

  • 糖果给你 2016-12-05 06:06
    最佳回答

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

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题