0

我正在尝试使用套接字建立 HTTPClient 连接,但无法弄清楚。当我运行代码时,我收到以下消息;

HTTP/1.1 400 Bad Request
Date: Sun, 22 Apr 2012 13:17:12 GMT
Server: Apache/2.2.16 (Debian)
Vary: Accept-Encoding
Content-Length: 317
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.2.16 (Debian) Server at pvs.ifi.uni-heidelberg.de Port 80</address>
</body></html>

代码在这里:

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

public class a1 {
  public static void main ( String[] args ) throws IOException {
    Socket s = null;

    try {
        String host = "host1";
        String file = "file1";
        int port = 80;

在这里,我正在创建套接字:

         s = new Socket(host, port);

        OutputStream out = s.getOutputStream();
        PrintWriter outw = new PrintWriter(out, false);
        outw.print("GET " + file + " HTTP/1.1\r\n");
        outw.print("Accept: text/plain, text/html, text/*\r\n");
        outw.print("\r\n");
        outw.flush();           

        InputStream in = s.getInputStream();
        InputStreamReader inr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(inr);
        String line;

        while ((line = br.readLine()) != null) {
                System.out.println(line);
        }

    } 
    catch (UnknownHostException e) {} 
    catch (IOException e) {}

        if (s != null) {
                try {
                        s.close();
                }
                catch ( IOException ioEx ) {}
        }
  }
}   

任何帮助将不胜感激。谢谢你。

4

1 回答 1

4

如果您真的非常想编写自己的 HTTP 客户端(比看起来更难,但很有教育意义),那么您缺少HostHTTP 1.1 中所需的标头:

outw.print("Host: " + host + ":" + port + "\r\n");

请参阅RFC 2616,第14.23 节。主持人

客户端必须在所有 HTTP/1.1 请求消息中包含 Host 头字段。

所以你的请求很糟糕,它错过了必需的Host标头。

于 2012-04-22T13:33:51.750 回答