从包含Cookie的网址中获取验证码图片

时间:2019-03-13 08:54:01

标签: java image cookies captcha

public Image GetPicture(String urlImg) {

    InputStream is = null;
    try {
        URL url = new URL(urlImg);
        URLConnection httpConn = url.openConnection();

        // Pass the input stream thorough a BufferedInputStream for better
        // efficiency
        is = new BufferedInputStream(httpConn.getInputStream());

        // Read the image and close the stream
        Image image = ImageIO.read(is);

        if (image == null) {
            System.err.println("ImageIO could not find a reader for this image");
            return null;
        }

        // Get the response cookies
        setCookies(httpConn.getHeaderFields().get("Set-Cookie"));
        return image;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
    return null;
}

这是用于设置Cookie的功能:

public void setCookies(List<String> cookies) {
    this.cookies = cookies;
}

用于检索:

public List<String> getCookies() {
    return cookies;
}

正在获取图片验证码以将其显示在jlabel上。这有意义吗? 我正在努力使功能更强大,而我所提出的只是您的建议。

0 个答案:

没有答案