I am learning about Java socket. I am trying to send an HTTPS GET request to Facebook, like this:
String request = "GET / HTTP/1.0\r\n"
+ "Host: www.facebook.com\r\n"
+ "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0\r\n"
+ "Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7\r\n"
+ "Accept-Language: de,en;q=0.7,en-us;q=0.3\r\n"
+ "Accept-Encoding: gzip\r\n"
+ "Connection: close\r\n\r\n";
byte[] Outdata = request.getBytes();
Socket server = new Socket("www.facebook.com", 443);
DataOutputStream outputStream = new DataOutputStream(server.getOutputStream());
outputStream.write(Outdata);
outputStream.flush();
And then, I try to listen to incoming data from the server, like this:
DataInputStream inputStream =
new DataInputStream(server.getInputStream());
byte[] InData = new byte[1024];
while (true) {
inputStream.read(InData);
String data = new String(InData, StandardCharsets.UTF_8);
System.out.println(data);
}
But I don't get any return data from the server. Why?
Two answers.
You are trying to talk to an HTTPS server. That requires you to establish an SSL/TLS channel. That is >>really difficult<< to do on a plain socket ... you'd have to implement the connection negotiation, the client-side validation of the key chain, the session encryption / decryption, and so on.
A more sane way would be to use SSLSocket, SSLSocketFactory and so on to handle the SSL/TLS stuff ... but it is still a bit tricky.
Talking to an HTTP or HTTPS service over a Socket is not a sensible approach. You are not really going to learn much by doing it, because the normal way to talk to an HTTP / HTTPS service from Java is to use
HttpURLConnection
, or the Apache HTTP libraries if you want more control.