日期:2014-05-20  浏览次数:20806 次

JAVA 在SWING 中显示网页上验证码图片的代码,谢谢
网页图片地址:http://www.uxin.com/captcha/index.html?t=123
我在网上找的方法显示到Jlabel中,结果无错误。正常得到图片数据到BYTE[]中。
就是无法看到图片,无错误提示。自己看了网页上图片的格式为PNG。这个我不确定是否正常,呵呵
希望有拉伸效果,比如它的大小是100X30,我想拉伸放到我组件大小为200X60上面。变型也不所谓,我要的是代码。因为是验证码,所以那种在JLABLE里面有什么HTML的就不要来了,必须保留SESSION。谢谢,我帖出我的代码。

try {
Date dt = new Date();
Long ldt = new Long(dt.getTime());
String strURL = "http://www.uxin.com/captcha/index.html?t="
+ ldt.toString();
URL url = new URL(strURL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream is = connection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int len = 0;
while ((len = is.read(buffer)) > 0) {
baos.write(buffer, 0, len);
}
is.close();
 byte[] bytImg = baos.toByteArray();
baos.close();

connection.disconnect();
lblImg.setIcon(new ImageIcon(bytImg));//这里没得显示,BYTE里面有数据
} catch (Exception ex) {

}

------解决方案--------------------
最大的问题在于你真的是拿到了图片吗?
执行下面的代码看看得到了什么。
        HttpURLConnection connection = (HttpURLConnection) new URL("http://www.uxin.com/captcha/index.html?t=" + new Date().getTime()).openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        InputStream response = connection.getInputStream();
        byte[] buf = new byte[1024];

        FileOutputStream out = new FileOutputStream("/Users/Biao/Desktop/x.html");

        int len = 0;
        while ((len = response.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        out.flush();
        out.close();