java.io.IOException:403错误加载URL jsoup登录

时间:2015-12-03 11:26:20

标签: java html-parsing jsoup

帮我jsoup登录,我必须登录,然后从登录页面重定向到另一个已保存会话的页面。

public void parseXhtml() throws IOException{
         String sessionID=null;
         Map<String, String> cookies = new HashMap<String, String>();
        cookies.put("login", "login");
        cookies.put("password", "password");
        Connection conn=Jsoup.connect("http://localhost:8080/dir/login.xhtml");

        Connection.Response res = Jsoup
                .connect("http://localhost:8080/dir/login.xhtml")
                .data(cookies)
                .execute();
        res = Jsoup.connect("http://localhost:8080/dir/dir/index.xhtml")
                .cookie("JSESSIONID", res.cookies().get("JSESSIONID"))
                .method(Method.GET)
                .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36")
                .execute();

         Document doc = res.parse();
         System.out.println(doc.html());
         sessionID = res.cookie("JSESSIONID");

         Document docu = Jsoup.connect("http://localhost:8080/dir/dir/index.xhtml")
                            .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36")
                            .cookie("JSESSIONID", res.cookies().get("JSESSIONID"))
                            .method(Connection.Method.GET)
                            .get();

它抛出以下异常

  

java.io.IOException:403错误加载网址http://localhost:8080/dir/dir/index.xhtml

如果我像[Sending POST request with username and password and save session cookie那样抛出相同的异常。

1 个答案:

答案 0 :(得分:0)

ExternalContext ec=FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest req=(HttpServletRequest) ec.getRequest();
        HttpSession sess=(HttpSession) ec.getSession(true);
        String url = req.getRequestURL().append(";jsessionid=").append(sess.getId()).toString();

        ec.setRequest("http://localhost:8080/dir/dir/index.xhtml");
        HttpServletRequest req2=(HttpServletRequest) ec.getRequest();
        String url2 = req2.getRequestURL().append(";jsessionid=").append(sess.getId()).toString();
        Document doc2=Jsoup.connect(url2).get();
        System.out.println(doc2.html());

最后我明白了,我不知道它是否正确,但是有效。