gpt4 book ai didi

java - 当我尝试发送请求时出现未知主机异常

转载 作者:行者123 更新时间:2023-12-02 06:45:51 25 4
gpt4 key购买 nike

我正在尝试检查是否有多个端口打开,以及 80 端口是否打开 - 发送 http 请求,然后在控制台中显示结果。每个端口都在自己的线程中进行检查。

我发送这样的请求

public static void send(Socket sock, String host) throws IOException{
PrintWriter pw = new PrintWriter(sock.getOutputStream());
pw.println("GET / HTTP/1.1");
pw.println("Host: " + host);
pw.println("");
pw.flush();
}

在类 TCPClient 中,我使用它并以字节形式返回结果,然后将其显示在控制台上。

    try {
sock = new Socket(host, port);
System.out.println("port " + port + " is in use");
// send request
HttpSender.send(sock, host);
BufferedReader bf = new BufferedReader(new InputStreamReader(sock.getInputStream()));
StringBuffer response = new StringBuffer();
String line = "";
while((line = bf.readLine()) != null) {
response.append(line);
response.append('\r');
}
bf.close();
return String.valueOf(response).getBytes(); // in method run I show it
} catch (SocketException e) {
return ("port " + port + " is free").getBytes();
}

我创建线程池用于端口检查。

public class ThreadPool {

private static int MAX_THREADS = 5;
private static String DESTINATION = "http://stackoverflow.com/";
private ExecutorService es = null;

public ThreadPool() {
es = Executors.newFixedThreadPool(MAX_THREADS);
}

public void perform(int start, int end) throws UnknownHostException {
for (int i = start; i <= end; i++) {
Runnable req = new TCPClient(DESTINATION, i);
es.execute(req);
}
es.shutdown();
while (!es.isTerminated()) {
}
;
System.out.println("all ports checked!");
}

}

当我将目的地设置为 www.stackoverflow.com 并获得带有文本的文档时,它已永久移动到 http://stackoverflow.com/。当我设置此目的地时 - 我遇到了 UnknownhostException

问题出在哪里?

最佳答案

您是否尝试过private static String DESTINATION = "stackoverflow.com";?字符串 "http://stackoverflow.com" 不是主机名,而是 URL。

关于java - 当我尝试发送请求时出现未知主机异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18645764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com