【问题标题】:Http Client hanging for some reasonHttp 客户端由于某种原因挂起
【发布时间】:2013-01-28 20:56:38
【问题描述】:

使用 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。它已启动并正常运行。我有我请求的文件存储在本地主机上。我可以通过浏览器访问它。

有什么想法可能会出错吗?

【问题讨论】:

    标签: java http netbeans httpclient wampserver


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多