javasocketssslhttpssslsocketfactory

Can't read any response with HTTPS GET request in Java


I have a problem with HTTPS requests, i want to make a very simple Java program for reading the response of a GET request. The problem is that i can't read any response, and the program prints nothing on screen.

This is the code:

import java.io.*;
import java.net.*;
import java.util.*;

import javax.net.ssl.*;


public class Test
{
  public static void main(String args[])
  {
    SSLSocket sock;
    String host = "www.example.com";

    try{
      SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
      sock = (SSLSocket) factory.createSocket(host, 443);

    }
    catch(IOException e)
    {
      e.printStackTrace();
      return;
    }

    try {

      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
      bw.write("GET / HTTP/1.1\r\n");
      bw.write("Accept: text/html\r\n");
      bw.write("User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\r\n");
      bw.write("\r\n");
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }



    try{
      BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      StringBuffer buffer = new StringBuffer();
      String temp;      
      while((temp = br.readLine()) != null)
      {
        buffer.append(temp);
      }
      br.close();
      System.out.println(buffer);
    }
    catch(IOException e)
    {
      e.printStackTrace();
      return;
    }

  }
}

I'm using SSLSocket with SSLSocketFactory, is there any procedure that i have to do in order to get the response from the server?


Solution

  • First, you need to call flush() to make sure the buffered data is actually written to the socket when you're ready.

      bw.write("GET / HTTP/1.1\r\n");
      bw.write("Accept: text/html\r\n");
      bw.write("User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\r\n");
      bw.write("\r\n");
      bw.flush();   // ADD THIS LINE
    

    Secondly, you need to send valid HTTP 1.1 headers. The RFCs are quite complicated, which is another reason to rely on well-regarded existing HTTP client libraries, but there is information here and elsewhere that should help, for example this. You are missing at least a Host: header for example.