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
Status code 400 means "Bad Request", so the client send something that was invalid or that the server did not understand. Can you add the value of the Cookie header that you set in your request?
以上就是Java Load image from URLConnection的详细内容,更多请关注web前端其它相关文章!