コード例 #1
0
ファイル: HttpSend.java プロジェクト: Jeanwin/study
  public static Map<String, String> login(
      HttpServletRequest req, HttpServletResponse res, String username, String password)
      throws Exception {
    String url = ReadProperties.getByName("login.ip") + "/login";
    Map<String, String> datas = new HashMap<String, String>();
    Map<String, String> cookies = new HashMap<String, String>();

    Connection con = Jsoup.connect(url).timeout(120000); // 获取连接
    con.header(
        "User-Agent",
        "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"); // 配置模拟浏览器
    Response rs;
    rs = con.execute();
    cookies = rs.cookies();
    Document doc = Jsoup.parse(rs.body()); // 转换为Dom树
    List<Element> et = doc.select("form"); // 获取form表单,可以通过查看页面源码代码得知
    for (Element e : et.get(0).getAllElements()) {
      if (e.attr("name").equals("username")) {
        e.attr("value", username); // 设置用户名
      }
      if (e.attr("name").equals("password")) {
        e.attr("value", password); // 设置用户密码
      }
      if (e.attr("name").length() > 0) { // 排除空值表单属性
        datas.put(e.attr("name"), e.attr("value"));
      }
    }
    // 设置cookie和post上面的map数据
    Response login = null;
    login = con.data(datas).cookies(cookies).method(Method.POST).execute();

    url = ReadProperties.getByName("common.ip") + req.getContextPath() + "/user/getUser";
    con =
        Jsoup.connect(url)
            .cookies(login.cookies())
            .ignoreContentType(true)
            .method(Method.GET); // 获取连接
    rs = con.execute();
    for (Entry<String, String> entry : rs.cookies().entrySet()) {
      Cookie cookie = new Cookie(entry.getKey(), entry.getValue());
      cookie.setPath(req.getContextPath() + "/");
      res.addCookie(cookie);
    }
    return JsonUtil.jsonToObject(rs.body(), Map.class);
  }