2010-07-29 77 views
0

我有一個URLConnection,訪問一個網頁。Java從URLConnection加載圖像

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

然後我把一些數據來使用

String headerValue = con.getHeaderField(6); 

我也得到了HTML,並從那裏解析圖像的URL使用con.setRequestProperty()

我得到的迴應餅乾來回MA指定字段服務器。但這是一個問題。當我訪問我的圖像時,我只能通過將緩存數據發送回服務器來獲取此映像。

於是我打開一個新的連接

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

我送餅乾回服務器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) 

預先感謝

+0

狀態碼400的意思是「錯誤的請求」,所以客戶端發送一些無效或服務器不理解的東西。您可以添加您在請求中設置的Cookie標頭的值嗎? – 2010-07-29 09:07:48

+0

哦,我在想這個,但只有在您的評論我嘗試修改cookis請求後。實際上服務器發送給我的cookies像「4ASP.NET_SessionId = 5gw3fg55ildrqs552q5qoa55; path = /; HttpOnly」,並且它要求我只發回4ASP.NET_SessionId = 5gw3fg55ildrqs552q5qoa55; ,沒有其他。 – artouiros 2010-07-29 09:39:24

回答

0

實測值的誤差。案件結案。 使用此代碼來分割Cookie字符串。

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

我愛幸福的結局:) – willcodejavaforfood 2010-07-29 09:43:28

+0

你也可以接受你自己的問題答案。如果您這樣做,請爲您的解決方案顯示一些代碼,即在將Cookie發送回去之前如何修改cookie值。 – 2010-07-30 20:59:59