码迷,mamicode.com
首页 > 编程语言 > 详细

如何获取网页验证码图片并保存到本地(Java实现) [问题点数:40分,结帖人lanxuezaipiao]

时间:2016-03-16 07:11:38      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

http://bbs.csdn.net/topics/390426978

public static String readCheckImage(HashMap<String, String> requestMap) {
        String url = requestMap.get("url");
        if (requestMap.get("params") != null) {
            url += "?" + requestMap.get("params");
        }
        InputStream in = null;
        try {
            System.out.println("get>>>" + url);

            URL serverUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
            conn.setRequestMethod("GET");// "POST" ,"GET"
            conn.addRequestProperty("Cookie", requestMap.get("cookie"));
            conn.addRequestProperty("Accept-Charset", "UTF-8;");// GB2312,
            conn.addRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
            conn.connect();
            // 判断请求是否成功
            if (((HttpURLConnection) conn).getResponseCode() == 200) {
                // 获取所有响应头字段
                Map<String, List<String>> map = conn.getHeaderFields();
                // 遍历所有的响应头字段
                for (String key : map.keySet()) {
                    System.out.println(key + "--->" + map.get(key));
                }
                // 返回的cookie
                String cookie = null;
                if (conn.getHeaderFields().get("Set-Cookie") != null) {
                    for (String s : conn.getHeaderFields().get("Set-Cookie")) {
                        cookie += s;
                    }
                }
                requestMap.put("cookie", requestMap.get("cookie") + cookie);
                in = conn.getInputStream();

                BufferedImage bi = ImageIO.read(in);
                File f = new File("check_img.jpg");
                ImageIO.write(bi, "jpg", f);

                return f.getAbsolutePath();
            } else {
                System.out.println("下载code图片失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }// 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }

如何获取网页验证码图片并保存到本地(Java实现) [问题点数:40分,结帖人lanxuezaipiao]

标签:

原文地址:http://www.cnblogs.com/donaldlee2008/p/5281972.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!