Java从URLConnection加载图像

时间:2010-07-29 08:41:13

标签: java url image bytearray urlconnection

我有一个访问网页的URLConnection。

URL url = new URL("https://domain");
   con = url.openConnection();
   con.setDoOutput(true);

然后我使用con.setRequestProperty()

将一些数据发送到服务器

我使用

从ma指定字段获取响应cookie
String headerValue = con.getHeaderField(6);

我也得到了html并从那里解析了一个图片网址。但这是一个问题。当我访问我的图像时,我只能通过将缓存数据发送回服务器来获取此图像。

所以我打开一个新连接

URL url1 = new URL("https://domain/image); 
    URLConnection con1 = url1.openConnection();

我将cookie发送回服务器con1.setRequestProperty("Cookie", headerValue);

最后我尝试使用BufferedInputStream访问图像,然后在JLabel中创建一个iamge

BufferedInputStream in = new BufferedInputStream(con1.getInputStream());
       ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
       int c;
       while ((c = in.read()) != -1) {
         byteArrayOut.write(c);
       }


       Image image = Toolkit.getDefaultToolkit().createImage(
               byteArrayOut.toByteArray());

    label.setIcon(new ImageIcon(image));

问题是这似乎不起作用。它是通过URlConnection从服务器获取文件的另一种方法吗? 错误代码

Server returned HTTP response code: 400 for URL: https://domain/image
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)

提前致谢

1 个答案:

答案 0 :(得分:0)

发现错误。案件结案。 使用此代码分割cookie字符串。

String temp = headerValue.substring(0, (len1-17));