0

サーバーがダウンすると、このスニペットはサーバーを繰り返し呼び出し続けます。リクエストが失敗した場合、繰り返しの呼び出しを停止するにはどうすればよいですか?多分キャッチ/エラーブロック?しかし、それを実装する方法がわかりません。ありがとう!

HttpURLConnection httpConn = null;
InputStream is = null;
OutputStream os = null;
String xmlResponse = null;

try {
   //Open Connection

       String CollectionId="123";
       String GetHTML="1";

       String urlString = "http://tester.com/webservices/ContentWS.asmx/GetCollection?CollectionId="+CollectionId+"&GetHTML="+GetHTML;

       System.out.println(urlString);

       //String encodedUrl = URLEncoder.encode(urlString,"UTF-8");

   URL url = new URL(urlString);
   httpConn = (HttpURLConnection)url.openConnection();

   //Setup Request
   httpConn.setRequestMethod("GET");
   httpConn.setDoOutput(true);
   httpConn.setReadTimeout(10000);
   httpConn.connect();

   xmlResponse = convertStreamToString(httpConn.getInputStream());
  }
  catch (IOException e) {
      e.printStackTrace();
   }

String htmlContent = "";
   try {
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
       DocumentBuilder db = dbf.newDocumentBuilder();
       InputSource input = new InputSource();
       input.setCharacterStream(new StringReader(xmlResponse));

       Document doc = db.parse(input);
       NodeList nodes = doc.getElementsByTagName("Item");

       // iterate the Items
               int i = 0;
               int j = 0;
               Date now = new Date();
       for (i = 0; i < 2; i++) {
                  //Grab HTML to append to htmlContent
                  NodeList teaser = doc.getElementsByTagName("Html");
                  Element line = (Element) teaser.item(i);
                  htmlContent += getCharacterDataFromElement(line);
       }
   }
   catch (Exception e) {
       e.printStackTrace();
   }
htmlContent = ...
4

2 に答える 2

0

このコードはスタック トレースを出力しますが、エラーをスローしないため、呼び出し元のコードは問題を認識しません。

catch() ブロックでエラーを再スローさせることは役に立ちますか?

e.printStackTrace();
throw e;
于 2012-04-12T18:16:07.540 に答える
0

すべてがうまくいくようです。あなたの接続は開かれており、機能していますが、細部を忘れています. HttpURLConnection.disconnect()接続からの情報の要求が終了したことをプログラムに伝えるために、終了時に使用する必要があります。

私は次のように Java の観点からネットワークを見ます: 接続をセットアップします --> 接続要求を送信します --> 接続されました --> データを取得します --> データで何かを行います --> 接続を閉じます

またHttpURLConnection.disconnect()、例外がスローされた場合でも切断されることを確認してください。} finally {必要に応じて、ステートメントを最後に追加してみてください。

于 2012-04-12T19:02:42.760 に答える