0

I was trying to get a web page using Socket and get request but I keep getting the same error - bad request, for any website or webpage i try to use it.

    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.0\n\n";
    //System.out.print(command);
    writer.print(command);
    writer.flush();

    while (reader.hasNextLine()) {
        System.out.println(reader.nextLine());
    }
    s.close();
Dragma
  • 54
  • 3
  • 7

1 Answers1

1

Try this :

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);
        }
    }
}
mehdi maick
  • 325
  • 3
  • 7