如何防止Jsoup在http错误上抛出异常?

时间:2017-07-27 20:38:56

标签: java android jsoup

我正在使用Jsoup制作应用程序,它将获取有关公共交通卡现金余额的信息。但是如果用户输入了错误的卡ID并且我的应用程序将其发送到网站,服务器将发送http错误409并将输出具有此ID的卡不存在。我设法写了这个简单的代码和平:

if (res1.statusCode() == 200) {
   doc1 = res1.parse();
   answer = doc1.body();
   title = answer.text();
} else if (res1.statusCode() == 409) {
  title = "Neteisingas kortelės numeris arba nepavyko patikrinti";
}

哪些内容写入String title,因为如果没有此解决方案,它会使title为空,这会导致代码的其他部分出现String tokenizer异常。 毕竟我已经问过如何防止Jsoup抛出异常?

我的例外:

07-27 23:30:12.831 22409-22427/com.bjobs.vvtcards W/System.err: org.jsoup.HttpStatusException: HTTP error fetching URL. Status=409, URL=https://mano.vilniustransport.lt/card/card-check?number=1231234566&_csrf_token=ke_q5dOIIzHCIB5OsuS-N6MlSLXh-im78brCfYn631c
07-27 23:30:12.831 22409-22427/com.bjobs.vvtcards W/System.err:     at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:682)
07-27 23:30:12.831 22409-22427/com.bjobs.vvtcards W/System.err:     at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:629)
07-27 23:30:12.831 22409-22427/com.bjobs.vvtcards W/System.err:     at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:261)
07-27 23:30:12.832 22409-22427/com.bjobs.vvtcards W/System.err:     at com.bjobs.vvtcards.MainActivity$2.run(MainActivity.java:183)
07-27 23:30:12.832 22409-22427/com.bjobs.vvtcards W/System.err:     at java.lang.Thread.run(Thread.java:761)

完整的Jsoup代码,如果你需要它:

 try {
                res = Jsoup.connect("https://mano.vilniustransport.lt/login")
                        .userAgent("Mozilla/5.0 (Linux; Android 7.1.1; LG-D855 Build/NOF26W) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36")
                        .ignoreHttpErrors(true)
                        .method(Connection.Method.GET)
                        .execute();
                doc = res.parse();
                Map welcomeCookies = res.cookies();
                Element inputHidden = doc.select("input").last();
                //String securityTokenKey = inputHidden.attr("name");
                String securityTokenValue = inputHidden.attr("value");
                for (int i = 0; i < cycleCounter; i++) {
                    String fullData = cardsNids.get(i);
                    String[] split = fullData.split("\n");
                    String cardNu = split[1];
                    Connection.Response res1 = Jsoup.connect("https://mano.vilniustransport.lt/card/card-check?number=" + cardNu + "&_csrf_token=" + securityTokenValue)
                            .header("Content-Type", "text/html; charset=UTF-8")
                            .userAgent("Mozilla/5.0 (Linux; Android 7.1.1; LG-D855 Build/NOF26W) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36")
                            .cookies(welcomeCookies)
                            .execute();
                    if (res1.statusCode() == 200) {
                        doc1 = res1.parse();
                        answer = doc1.body();
                        title = answer.text();
                    } else if (res1.statusCode() == 409) {
                        title = "Neteisingas kortelės numeris arba nepavyko patikrinti";
                    }
                    String presentData = cardsNids.get(i);
                    cardsNids.set(i, presentData + "\n" + title);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

更新代码:

private void checkBalance() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                res = Jsoup.connect("https://mano.vilniustransport.lt/login")
                        .userAgent("Mozilla/5.0 (Linux; Android 7.1.1; LG-D855 Build/NOF26W) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36")
                        .ignoreHttpErrors(true)
                        .method(Connection.Method.GET)
                        .execute();
                doc = res.parse();
                Map welcomeCookies = res.cookies();
                Element inputHidden = doc.select("input").last();
                //String securityTokenKey = inputHidden.attr("name");
                String securityTokenValue = inputHidden.attr("value");
                for (int i = 0; i < cycleCounter; i++) {
                    String fullData = cardsNids.get(i);
                    String[] split = fullData.split("\n");
                    String cardNu = split[1];
                    res1 = Jsoup.connect("https://mano.vilniustransport.lt/card/card-check?number=" + cardNu + "&_csrf_token=" + securityTokenValue)
                            .header("Content-Type", "text/html; charset=UTF-8")
                            .userAgent("Mozilla/5.0 (Linux; Android 7.1.1; LG-D855 Build/NOF26W) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36")
                            .cookies(welcomeCookies)
                            .execute();

                        doc1 = res1.parse();
                        answer = doc1.body();
                        title = answer.text();
                    String presentData = cardsNids.get(i);
                    cardsNids.set(i, presentData + "\n" + title);
                }
            } catch (HttpStatusException e) {
                if (res1.statusCode() == 409) {
                    title = "Neteisingas kortelės numeris arba nepavyko patikrinti";
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            // Update the progress bar
            mHandler.post(new Runnable() {
                public void run() {
                    adapter = new RecyclerAdapter(createList(cardsNids.size()));
                    recyclerView.setAdapter(adapter);
                }
            });
        }
    }).start();
}

现在我又收到了另一个错误:

07-28 20:56:51.328 21205-21242/com.bjobs.vvtcards E/AndroidRuntime: FATAL EXCEPTION: Thread-4
                                                                    Process: com.bjobs.vvtcards, PID: 21205
                                                                    java.lang.NullPointerException: Attempt to invoke interface method 'int org.jsoup.Connection$Response.statusCode()' on a null object reference
                                                                        at com.bjobs.vvtcards.MainActivity$2.run(MainActivity.java:194)
                                                                        at java.lang.Thread.run(Thread.java:761)

2 个答案:

答案 0 :(得分:3)

当Jsoup失败时,它会引发一个您没有捕到的异常 - 您的代码只捕获IOException,但在您的堆栈跟踪中,您有一个HttpStatusException。在第一个catch之后添加第二个catch子句:

catch (HttpStatusException e) {
    if (res1.statusCode == 409) {
        //handle the exception
    }
}

答案 1 :(得分:1)

试试这个:

catch (HttpStatusException e) {
    if (res1 != null && res1.statusCode == 409) {
        //handle the exception
    }
}