Reputation: 26465
I'm trying to do some HTTP manually by opening a TCP socket, send the request and read/print the response message. The content of the response body is well printed , but the main thread never exits and blocks forever.
socket = new Socket(host, port);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.print(request);
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
reader.lines().forEach(System.out::println);
// String next_record = null;
// while ((next_record = reader.readLine()) != null)
// System.out.println(next_record);
socket.close();
// System.out.println("Finished");
What am I missing, and how can I fix it ?
Upvotes: 2
Views: 730
Reputation: 10414
Are you making sure you're sending the HTTP request correctly? This works for me. Note the "Connection: Close\r\n" string was important otherwise it hangs for me too after reading the content.
import java.net.Socket;
import java.io.PrintWriter;
import java.io.*;
public class App {
public static void main(String[] args) throws Exception {
String host = "google.com";
int port = 80;
Socket socket = new Socket(host, port);
//BufferedWriter writer = new BufferedWriter(
// new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.write("GET / HTTP/1.1\r\n");
writer.write("Connection: Close\r\n");
writer.write("\r\n");
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
// reader.lines().forEach(System.out.println);
String line;
System.out.println("Reading lines:");
while ((line = reader.readLine()) != null) {
System.out.println("* " + line);
}
System.out.println("DONE READING RESPONSE");
reader.close();
writer.close();
// socket.close();
System.out.println("Finished");
}
}
Upvotes: 2