Reputation: 2121
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
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