Java 从 URLConnection 加载图像
我有一个 URLConnection,可以访问网页。
URL url = new URL("https://domain");
con = url.openConnection();
con.setDoOutput(true);
然后我使用 con.setRequestProperty() 向服务器发送一些数据,
我使用指定字段获取响应 cookies,
String headerValue = con.getHeaderField(6);
我还获取 html 并从那里解析图像 url。但这里有一个问题。当我访问我的图像时,我只能通过将缓存数据发送回服务器来获取此图像。
因此,我打开一个新连接,
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)
提前致谢
I have a URLConnection, that access a web page.
URL url = new URL("https://domain");
con = url.openConnection();
con.setDoOutput(true);
Then i sent some data to the server using con.setRequestProperty()
I get the response cookies fro ma specified field using
String headerValue = con.getHeaderField(6);
I also get the html and parse an image url from there. But here is a problem. I can get this image only by sending cache data back to the server ,when i acces my image.
So i open a new connection
URL url1 = new URL("https://domain/image);
URLConnection con1 = url1.openConnection();
I send the cookies back to the server con1.setRequestProperty("Cookie", headerValue);
And finally i try to acces the image using BufferedInputStream and then creating an iamge in a JLabel
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));
The problem is this seems to not work. Is it another way to get an file from a server through a URlConnection?
Error code
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)
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发现错误了。案件结案。
使用此代码来分割 cookie 字符串。
Found the error. Case closed.
Used this code to split the cookies string.