2017-08-04 4 views
0

私はjavaエキスパートではありません。java、アプレット内でHttpURLConnectionのパフォーマンスを使用してメソッドを増やす方法

ローカルWebサーバーの応答を要求するコードがあります。 私はjavaアプリケーション/ jarで行っています。 これは、少なくとも私のマシンでで動作します。 :)ローカルサーバーからの返信でエラーが0です。

私のクライアントはのコードをアプレットに使用しました:Java Tomcatで再コンパイル、署名、デプロイしました。

クライアント側から10コールごとに1つのエラーがあります。

アプレットのパフォーマンスを向上させるためのアドバイスはありますか?

/* 
    "ruta" opcion a pedirle al servidor python para que ejecute. 
    jTextArea_respuesta: El Objeto Swing de la ventana donde escribir la respuesta 
    enDebug: muestra informes en consola de java, true o false. 
*/ 
public boolean enviaPeticion(javax.swing.JTextArea Jtextarea_respuesta, boolean enDebug, String mi_opcion) { 

    long startTime=0; 
    long endTime=0; 

    if(enDebug==true) 
    { 
     startTime = System.currentTimeMillis(); 
    } 

    boolean todo_funciono = false; 

    //la direccion local del servidor python 
    String url = "http://localhost:8080/?opcion=" + mi_opcion; 

    //codigo de respuesta http 
    int responseCode = 0; 

    URL obj; 
    try { 

     //crea objeto de url    
     obj = new URL(url); 

     HttpURLConnection con; 
     try { 

      //abre conexion     
      con = (HttpURLConnection) obj.openConnection(); 

      // solo interesa el metodo GET 
      con.setRequestMethod("GET"); 

      //no es necesario indicar el agente 
      //con.setRequestProperty("User-Agent", USER_AGENT); 
      responseCode = -1; 

      try { 

       //se obtiene el código de respuesta http 
       responseCode = con.getResponseCode(); 

      } catch (java.net.ConnectException ex) { 

       if (enDebug) { 
        Logger.getLogger(Frame.class.getName()).log(Level.WARNING, null, ex); 
       } 

       //si esto falla lo más problable es que no este activo el programa servidor 
       if (Jtextarea_respuesta != null) { 
        Jtextarea_respuesta.setText("servidor caido"); 
       } 

       return false; 
      } 

      //se procesa la respuesta del servidor web 
      BufferedReader in = null; 
      try { 
       in = new BufferedReader(
         new InputStreamReader(con.getInputStream())); 
      } catch (IOException ex) { 
       if (enDebug) { 
        Logger.getLogger(Frame.class.getName()).log(Level.WARNING, null, ex); 
       } 

       return false; 
      } 

      String inputLine; 
      StringBuffer response = new StringBuffer(); 

      while ((inputLine = in.readLine()) != null) { 
       response.append(inputLine); 
      } 

      in.close(); 

      // System.out.println(response.toString()); 
      //System.out.println("Response Code : " + responseCode); 
      // si el código de respuesta del servidor es 200 
      // es porque el servidor esta activo y la opción ingresada es válida 
      if (responseCode == 200) { 

       //se procesara un par opcion-valor con los datos xml recibidos 
       HashMap<String, String> values = new HashMap<String, String>(); 
       String xmlString = response.toString(); 
       Document xml = convertStringToDocument(xmlString); 
       Node user = xml.getFirstChild(); 
       NodeList childs = user.getChildNodes(); 
       Node child; 
       for (int i = 0; i < childs.getLength(); i++) { 
        child = childs.item(i); 
        //System.out.println(child.getNodeName()+" "+child.getTextContent()); 

        //obtiene un par llave-valor 
        values.put(child.getNodeName(), child.getTextContent()); 
       } 

         if(enDebug==true) 
         { 
          endTime = System.currentTimeMillis(); 
         } 


       if (mi_opcion.equals("entrada")) { 
        //System.out.println(values.get("positivo")); 

        // esta es la respuesta positiva esperada 
        try { 
         if (values.get("positivo").equals("True")) { 
          //  
          // **** fue procesada la entrada en el hardware 
          //  
          if (Jtextarea_respuesta != null) { 

           String duracion=""; 


          if(enDebug==true) 
          { 
           // calcula cuanto se tardó en responder el servidor python 
           duracion = "\n"+"peticion tardó "+ Long.toString(endTime - startTime) + " milisegundos"; 
          } 

           Jtextarea_respuesta.setText("enviada entrada "+ duracion); 
          } 

          //podemos reportar que funciono la operacion 
          todo_funciono = true; 
         } 
        } catch (Exception e) { 
         if (enDebug) { 
          //la respuesta xml no contiene <positivo> 
          Logger.getLogger(Frame.class.getName()).log(Level.FINE, null, e); 
         } 
        } 

        try { 

         // en esta situacion hay un error como el dispositivo desconectado 
         String error = values.get("error"); 

         if (!error.isEmpty()) { 
          //  
          // **** ocurrio algun error al solicitar la entrada 
          // 
          if (Jtextarea_respuesta != null) { 
           Jtextarea_respuesta.setText(error); 
          } 

          return false; 
         } 
        } catch (Exception e) { 
         if (enDebug) { 
          // la respuesta xml no contiene <error> 
          Logger.getLogger(Frame.class.getName()).log(Level.FINE, null, e); 
         } 

        } 
       } 

      } else { 
       if (Jtextarea_respuesta != null) { 

        // alguna otra situación por la cual falle el proceso 
        // mi_opcion no es válida 
        Jtextarea_respuesta.setText("opcion invalida o error interno"); 
        return false; 
       } 
      } 

     } catch (IOException ex) { 

      //no se pudo abrir la conexion por permisos de Java o el applet. 
      if (enDebug) { 
       Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex); 
      } 

     } 

    } catch (MalformedURLException ex) { 

     // en caso que la url haya sido mal escrita. 
     // caso improblable. 
     if (enDebug) { 
      Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

    //Jtextarea_respuesta.setText("Enviando peticion a " + url); 
    return todo_funciono; 

} 
+2

なぜあなたはアプレットを作成していますか?彼らはもう誰にも支持されていません。 –

+0

finallyブロックを追加し、con.disconnect()を使用して開いている接続を閉じます。あなたの接続のBTW設定タイムアウト – Arung

+0

ありがとう。ジョー。 //アプレットは単なる要求条件です。 – Ando

答えて

0

あなたはStringBuilderを削除し、ストレート接続の入力ストリームからXMLを解析することによってパフォーマンスを増やすことができます。これは、時間と空間の両方を節約します。

サーバー障害の発生率をクライアントのコード変更によって減らすことはできません。

このうちのいくつかにはXPathを使用する必要があります。

関連する問題