0

使用 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();

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

任何想法可能出了什么问题?

4

1 回答 1

1

没有 CR 或 LF 是您的问题之一。您应该编写 ASCII 字符并且可能是 Host 标头。

outToServer.write(("GET " + path + " HTTP/1.0\r\n").getBytes("ASCII"));
outToServer.write("Host: myhost.com\r\n\r\n".getBytes("ASCII"));
outToServer.flush();
于 2013-01-28T21:27:34.313 回答