在 java 中发出 http 请求时收到 400 个错误的请求

时间:2021-02-24 09:03:56

标签: java html http web

我正在制作一个 Java 程序,它发出 http get 请求并下载一个 html 文件。这是我的代码

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

public class HTTP {

public static void main(String[] args) {
    try {
        FileOutputStream to_file = new FileOutputStream("f:\\temp.txt");
        URL url = new URL("http://www.dailygames.com/3dgames.html");

        String host = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            port = 80;
        }

        String filename = url.getFile();
        System.out.println(filename);

        //Create Connection
        //Open socket to a specific host and port
        Socket socket = new Socket(host, port);

        //Get input and output streams for the socket
        InputStream from_server = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();

        // Get response OR Instantiates a new PrintWriter passing in the sockets output stream
        PrintWriter to_server = new PrintWriter(outputStream);

        // Send headers OR Prints the request string to the output stream
        to_server.println("GET " + filename + " HTTP/1.1"); // This is a message sent to the server
        to_server.println("Host: " + host + "\r\n"); // As you can see, the domain name is passed to the program as an argument. After connected to the server, it sends the domain name, and reads the response from the server.
        to_server.flush();

        byte[] buffer = new byte[4096];
        int byte_read;

        //Reads & Prints each line of the response OR Reads HTTP response
        while ((byte_read = from_server.read(buffer)) != -1) {
            // Print server's response
            to_file.write(buffer, 0, byte_read);
            System.out.print((char) byte_read);
        }
        socket.close();
        to_file.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

当我运行这段代码时,它会创建一个文本文件,但是当我打开它时,响应不是 html 文件而是 400 错误响应。我该如何解决这个问题

enter image description here

0 个答案:

没有答案