我当前正在发送如下所示的请求,并希望打印出响应并退出。是否有一种可靠的方法来获取整个响应然后退出,即,而不是在 x
行或 x
秒后中断循环(这会出现问题)?目前,程序永远不会退出,因为 Scanner
会阻塞等待更多输入。如果不使用某种可能会阻塞的循环/读取器组合,我还能如何打印响应?
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();
}
}
最佳答案
我不是百分百确定你想在这里做什么。 但如果您只想获取应答页面的 html 并随后继续,请尝试以下代码示例:
/**
* 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();
}
}
关于java - 如何打印出HTTP响应然后退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18850740/