bqui56
bqui56

Reputation: 2121

How to print out HTTP response and then exit

I am currently sending a request as shown below and was wanting to print out the response and exit. Is there a robust way of getting the whole response and then exiting, i.e., rather than breaking the loop after x lines or x seconds (which would have problematic cases)? Currently, the program never exits as the Scanner blocks waiting for more input. How else can I print out the response if not with some kind of loop/reader combination that might block?

public class PingHost {
   public static void main(String[] args) throws Exception {
      Socket s = new Socket("www.google.com", 80);
      DataOutputStream out = new DataOutputStream(s.getOutputStream());
      out.writeBytes("GET / HTTP/1.1\n\n");
      Scanner sc = new Scanner(s.getInputStream());
      while (sc.hasNext())
         System.out.println(sc.nextLine());
      System.out.println("never gets to here");
      s.close();
   }
}

Upvotes: 0

Views: 235

Answers (1)

happyburnout
happyburnout

Reputation: 139

I am not 100 percent sure what you wanna do here. But if you wanna just get the html of the answering page and move on afterwards, then give this code sample a try:

/**
 * Example call:<br>
 * sendHTTPRequestAndSysoutData("http://www.google.com"); 
 * @param target
 */

public static void sendHTTPRequestAndSysoutData(String target){
    try{
        URL my_url = new URL(target);
        BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));
        String strTemp = "";
        while (null != (strTemp = br.readLine())){
            System.out.println(strTemp);
        }
    }
    catch(IOException e){
        e.printStackTrace();
    }
}

Upvotes: 1

Related Questions