Java Http Client获得408请求超时

时间:2014-06-26 06:16:23

标签: java http request client

我正在开发一个简单的http客户端,但我有问题:

在Windows命令行上使用 telnet 时:

telnet download.microsoft.com 80


HEAD / HTTP/1.1
Host: download.microsoft.com

回复:301永久移动

HEAD /download/7/A/9/7A9EBB22-8DC8-40A2-802D-B4CC343A928E/proplussp2013-kb2817430-fullfile-x86-vi-vn.exe HTTP/1.1
Host: download.microsoft.com

回复:200 OK

使用我的程序时(Eclipse IDE,JRE8) 这是我的Java代码:

import java.io.*;
import java.net.*;

public class Main {
    public static DataInputStream in;
    public static BufferedWriter out;
    public static String host = "download.microsoft.com";
    public static int port = 80;
    public static Socket soc;

    public static String getHeader(String uri) throws IOException{

        String httpRequest = "HEAD " + uri + "\r\n"
                + "HTTP/1.1\r\n"
                + "Host:" + host
                + "\r\n";
        String httpResponse = "";
        int read;

        out.write(httpRequest);
        out.flush();

        while ((read = in.read()) != -1)
            httpResponse += (char)read;

        return httpResponse;
    }

    public static void main(String[] args) throws UnknownHostException, IOException{
        soc = new Socket(host, port);
        in = new DataInputStream(soc.getInputStream());
        out= new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())); 

        System.out.println(getHeader("/"));

        soc.close();
    }
}

使用getHeader("/")运行大约20秒然后响应HTTP / 1.0 408请求超时

使用getHeader("/download/7/A/9/7A9EBB22-8DC8-40A2-802D-B4CC343A928E/proplussp2013-kb2817430-fullfile-x86-vi-vn.exe"),它还会获得HTTP / 1.0 408请求超时

我的代码与其他主机一起工作正常。我也知道主机download.microsoft.com不能正常访问,但为什么上面的2方法会给出不同的结果呢?

谢谢!

1 个答案:

答案 0 :(得分:0)

将httpRequest的内容转储到屏幕上,你会发现你正在构建一个损坏的请求(在http版本之前CRLF而不是SP)。

此外,您错过了额外的CRLF(请参阅http://greenbytes.de/tech/webdav/rfc7230.html#http.message