简体   繁体   中英

How to prevent Jsoup from throwing exception on http error?

I am using Jsoup to make app which will get info about public transport card cash balance. But if user input incorrect card ID and my app send it to website, server will send http error 409 and will output that card with such ID doesn't exist. I managed to write this simple peace of code:

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";
}

Which writes something to the String title , because without this solution, it leave title empty, which leads to String tokenizer exception in other part of code. After all this I have come with question

My exception:

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)

And full Jsoup code, if you need it:

 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();
}

And now Im getting another error:

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)

When Jsoup fails, it throws an exception which you don't catch - your code only catches an IOException , but in your stacktrace you have a HttpStatusException . Add a second catch clause after the first catch :

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

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM