gpt4 book ai didi

java - Http 客户端由于某种原因挂起

转载 作者:行者123 更新时间:2023-12-01 14:53:25 26 4
gpt4 key购买 nike

使用 Netbeans 开发 HTTP 客户端程序。

到目前为止,我已经在 HttpClient 类中到达这里:

public class MyHttpClient {

MyHttpRequest request;
String host;

public MyHttpResponse execute(MyHttpRequest request) throws IOException {

//Creating the response object
MyHttpResponse response = new MyHttpResponse();

//Get web server host and port from request.
String host = request.getHost();
int port = request.getPort();

//Check 1: HOST AND PORT NAME CORRECT!
System.out.println("host: " + host + " port: " + String.valueOf(port));

//Get resource path on web server from requests.
String path = request.getPath();

//Check 2: ENSURE PATH IS CORRECT!
System.out.println("path: " + path);

//Open connection to the web server
Socket s = new Socket(host, port);

//Get Socket input stream and wrap it in Buffered Reader so it can be read line by line.
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(s.getInputStream()));

//Get Socket output stream and wrap it in a DataOutputStream so it can be written to line by line.
DataOutputStream outToServer = new DataOutputStream(s.getOutputStream());

//Get request method
String method = request.getMethod();

//Check 3: ENSURE REQUEST IS CORRECT GET/POST!
System.out.println("Method: " + method);

//GET REQUEST

if(method.equalsIgnoreCase("GET")){
//Send request to server
outToServer.writeChars("GET " + path + " HTTP/1.0");

//HTTP RESPONSE
System.out.println("WAITING FOR RESPONSE!");

String line = inFromServer.readLine();
System.out.println("Line: " + line);


}

//Returning the response
return response;

}

}

我已检查以确保我的请求行构造正确,如整个打印语句中所示。但是,当我到达这一行时,程序挂起:

System.out.println("WAITING FOR RESPONSE!");

String line = inFromServer.readLine();

我不知道为什么...我的服务器是本地主机 WAMP。它已正常启动并运行。我将我请求的文件存储在本地主机上。我可以通过浏览器访问它。

有什么想法可能会出问题吗?

最佳答案

没有 CR 或 LF 是你的问题之一。您应该编写 ASCII 字符,并且可能是主机 header 。

outToServer.write(("GET " + path + " HTTP/1.0\r\n").getBytes("ASCII"));
outToServer.write("Host: myhost.com\r\n\r\n".getBytes("ASCII"));
outToServer.flush();

关于java - Http 客户端由于某种原因挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14571089/

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