mercredi 24 février 2021

Getting 400 bad request when making a http request in java

I'm making a Java program which makes http get request and downloads a html file.Here is my code

  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();
    }
}
}

When I run this code It creates a text file but when I open it the response is not the html file but a 400 error response.How can I solve this problem

enter image description here




Aucun commentaire:

Enregistrer un commentaire