尝试使用套接字检索页面时,请继续获取相同的错误代码(不良请求)



我正在尝试使用套接字获取网页并获取请求,但我会遇到相同的错误 - 不良请求,对于任何网站或网页,我都尝试使用它。

    Socket s = new Socket("horstmann.com", 80);
    InputStream in = s.getInputStream();
    OutputStream out = s.getOutputStream();
    Scanner reader = new Scanner(in);
    PrintWriter writer = new PrintWriter(out, false);
    String command = "GET / HTTP/1.0nn";
    //System.out.print(command);
    writer.print(command);
    writer.flush();
    while (reader.hasNextLine()) {
        System.out.println(reader.nextLine());
    }
    s.close();

尝试以下:

import java.net.*;
import java.io.*;
class ScoketQuestion {
    public static void main(String[] args) {
        try {
            final String URL = "";
            Socket s = new Socket(URL, 80);
            DataInputStream dIn = new DataInputStream(s.getInputStream());
            PrintWriter wtr = new PrintWriter(s.getOutputStream());
            wtr.println("GET / HTTP/1.1");
            wtr.println("Host: " + URL);
            wtr.println("");
            wtr.flush();
            byte[] data = new byte[1024];
            int pt = 0;
            String str;
            while (true) {
                pt = dIn.read(data);
                if (pt == -1) break;
                str = new String(data, 0, pt);
                System.out.println(str);
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

最新更新