要登录的站点是自己搭建的,比较简单, 有验证码, 只要提交了正确的验证码就算登录成功。
我是这样做的:先通过httpget 把登录页面代码取出来, 再获取验证码的地址
然后把验证码显示出来让用户自己输入
显示验证码这块是用以下代码实现:
- Java code
imageBox = imageBox = new ImageBoxPanel2(ImageIO.read(new URL(getURL())));
因为用的URL 这个类, 所以实际获取验证码时的session没有在httpclient中, 所以模拟的post怎么也成功不了
有什么方法是用httpclient把验证码取出来显示给用户?
下面是要登录站点的部分代码:
产生验证码的servlet
- Java code
public class image extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage image = new BufferedImage(30, 15, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random r = new Random(); int n = r.nextInt(9000) + 1000; System.out.println("产生的验证码是: " + n); g.drawString(n + "", 0, 10); request.getSession().setAttribute("verifycode", n + ""); ImageIO.write(image, "gif", response.getOutputStream()); }}
这是判断登录成功的servlet:
- Java code
public class login extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String verifycode = request.getParameter("verifycode");//这个是通过httppost传过来的 String verifycode2 = (String) request.getSession().getAttribute("verifycode"); System.out.println(verifycode); System.out.println(verifycode2); if(verifycode.equals(verifycode2)) { out.print("success"); } else { out.print("error"); } out.flush(); out.close(); }}
------解决方案--------------------
你用ImageIO.read的话,会得不到JSessionId,所以后面就没法继续会话了。
用HttpClient提取验证码并不难啊,无非是你要自己生成Image对象而已,这里有例子:
http://blog.csdn.net/autofei/article/details/5710201