使用Thread管理UnknownHostException

时间:2015-12-09 11:47:05

标签: java exception javafx google-api task

我在JavaFx中使用自定义搜索API开发了一个小应用程序。

如下图所示,用户在文本字段中插入“researchkey”,然后按“cerca”,此时在Custom Search API的帮助下,我会显示结果图片。显示的示例是“home”。 enter image description here

有时我有这个问题,我得到了这个例外。 enter image description here

我知道应该是因为dns,我看到其他人也有同样的问题。我想通过“警告”来管理这个例外,当我得到这个例外时,我希望显示类似“你必须重复研究,对不起”的内容。我使用线程管理了自定义搜索Api,因为我在API运行时显示其他“图片”

这里的代码。

public class FinestradiRicerca extends Pane {

    GridPane resultgrid = new GridPane(); // griglia per risultati
    int j=0;
    int k = 0 ;
    private int i;
    private BufferedImage image;
    DialogStage parent;
    ImageView load;
    ImageView icon1 = new ImageView(new Image("img/back_load.png", true));
    ImageView close;
    ImageView cerca;
    ArrayList<String> result;
    VBox stack;
    VBox vbox;
    TextField userTextField;
    GridPane researchgrid;

    final private static String GOOGLE_SEARCH_URL = "https://www.googleapis.com/customsearch/v1?";

    // api key
    final private static String API_KEY = "api key";

    // custom search engine ID
    final private static String SEARCH_ENGINE_ID = "custom search engine ID";

    final private static String search_Type = "image";

    final private static String FINAL_URL = GOOGLE_SEARCH_URL + "key=" + API_KEY + "&cx=" + SEARCH_ENGINE_ID
            + "&searchType=" + search_Type;

    Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
    double maxscreenwidth = screensize.getWidth();
    double maxscreenheight = screensize.getHeight();
    int textdimension= (int)maxscreenwidth/70;
    int xclose = (int)maxscreenwidth/14;
    int xcerca = (int)maxscreenwidth/50;

        public FinestradiRicerca(double w, double h, DialogStage p){

            setVisible(true);
            parent = p;
            stack = new VBox();
            stack.setPrefSize(w, h);

            cerca = new ImageView(new Image("img/button_cerca_rid.png"));
            close = new ImageView(new Image("img/button_close.png"));
            userTextField = new TextField();
            userTextField.setPromptText("<Inserisci Testo>");
            userTextField.setPrefColumnCount(20);
            userTextField.setFocusTraversable(false);


            researchgrid = new GridPane();
            researchgrid.setLayoutX(0);
            researchgrid.setLayoutY(0);
            researchgrid.setAlignment(Pos.BASELINE_LEFT);
            researchgrid.setPadding(new Insets(5));
            researchgrid.setHgap(10);
            researchgrid.setVgap(10);
            researchgrid.add(userTextField, textdimension, 0);
            researchgrid.add(cerca, xcerca, 0);
            researchgrid.add(close,xclose, 0);
            setStyle("-fx-background-color: #858585;");
            stack.getChildren().add(researchgrid);

            getChildren().add(stack);

            load = new ImageView("img/back_load_pdf.jpg");
            load.setFitWidth(w);
            load.setFitHeight(h);
            load.setLayoutX(0);
            load.setLayoutY(0);
            getChildren().add(load);
            load.setVisible(false);

            Task<Boolean>  task = new Task<Boolean>   (){

                @Override
                protected Boolean call() throws Exception {
                    // TODO Auto-generated method stub
                    load.setVisible(true);
                    String searchKeyWord = userTextField.getText();
                    result = getSearchResult(searchKeyWord);
                    return null;



                }
            };

            task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                @Override
                public void handle(WorkerStateEvent t) {


                    for ( i=0; i<result.size(); i++)

                    {
                            System.out.println("" +result.get(i)); 
                            ImageView resultview;
                            resultview = new ImageView(result.get(i)); 
                            resultview.setFitWidth(130);
                            resultview.setFitHeight(130);

                              if(j==4)
                                      {
                                        j=0;
                                        k++;
                                      }

                               resultgrid.add(resultview, j,k );
                               j++;

                        resultgrid.setHgap(50);
                        resultgrid.setVgap(50);
                        vbox = new VBox();
                        vbox.getChildren().add(resultgrid);
                        vbox.setSpacing(10);
                        vbox.setPadding(new Insets(90, 0, 10, 220)); //TOP RIGHT BOTTOM LEFT
                        getChildren().add(vbox);


                        final int ind = i;
                        resultview.setOnMouseClicked((ev) ->{


                             if (ev.getClickCount()==2)
                             {

                                image = SwingFXUtils.fromFXImage(resultview.getImage(), null);
                                parent.setCrop(image);

                    }

                    });

                    }
                    load.setVisible(false);
                }

            }); 

            task.setOnFailed(new EventHandler<WorkerStateEvent>() {
                @Override
                public void handle(WorkerStateEvent t) {
                    // Code to close the previous dialog
                    System.out.println("Errore, ripetere la ricerca");
                     load.setVisible(false);

                }
            });         


            cerca.setOnMouseClicked(new EventHandler<MouseEvent>() {

                @Override
                public void handle(MouseEvent event) {
                         Thread th = new Thread(task);
                    th.start();

                }
            });


            close.setOnMouseClicked(new EventHandler<MouseEvent>() {

                   @Override
                   public void handle(MouseEvent event) {
                  parent.close();
                   }
                  });   

    }

        public ArrayList<String> getSearchResult(String keyword) {

            ArrayList<String> resultList = new ArrayList<>();

            try {
                URL url = new URL(FINAL_URL + "&q=" + keyword);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                // conn.setDefaultRequestProperty("Accept", "application/json");
                conn.setDoOutput(true);

                // 10 secondi per rispondere prima che vada in timeout
                conn.setReadTimeout(10 * 1000);
                conn.connect();

                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                String output;
                while ((output = br.readLine()) != null) // Leggo riga per riga
                                                            // fintanto chè non ce
                                                            // ne sono più
                {
                    if (output.contains("\"link\": \"")) {
                        String link = output.substring(output.indexOf("\"link\": \"") + ("\"link\": \"").length(),
                                output.indexOf("\","));
                        resultList.add(link);

                    }
                }
                conn.disconnect();

            } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return resultList;

        }
        public BufferedImage getImage(){
            return image;
        }



}

0 个答案:

没有答案