0

現在、以下に示すようにリクエストを送信しており、レスポンスを印刷して終了したいと考えていました。応答全体を取得してから終了する堅牢な方法はありますxx? 現在、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();
   }
}
4

1 に答える 1

1

あなたがここで何をしたいのか、私には 100% 確信が持てません。ただし、応答ページの 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();
    }
}
于 2013-09-17T14:01:37.573 に答える