Setting custom HTTP request headers in the URL object does not work

I am trying to get an image from an IP camera using HTTP. The camera requires basic HTTP authentication, so I have to add the appropriate request header:

URL url = new URL("http://myipcam/snapshot.jpg"); URLConnection uc = url.openConnection(); uc.setRequestProperty("Authorization", "Basic " + new String(Base64.encode("user:pass".getBytes()))); // outputs "null" System.out.println(uc.getRequestProperty("Authorization")); 

I later pass the url object to ImageIO.read() , and as you can guess, I get HTTP 401 Unauthorized, although user and pass are correct.

What am I doing wrong?

I also tried new URL("http://user: pass@myipcam /snapshot.jpg") , but this also does not work.

+6
source share
3 answers

The problem is resolved. This did not work because I was passing the url to ImageIO.read() .

Instead, passing uc.getInputStream() made it work.

+1
source

In the sun.net.www.protocol.http.HttpURLConnection class, which extends java.net.HttpURLConnection , the following getRequestProperty(String key) method getRequestProperty(String key) been overridden to return null when requesting security for sensitive information.

 public String getRequestProperty(String key) { // don't return headers containing security sensitive information if (key != null) { for (int i = 0; i < EXCLUDE_HEADERS.length; i++) { if (key.equalsIgnoreCase(EXCLUDE_HEADERS[i])) { return null; } } } return requests.findValue(key); } 

Here is the announcement for EXCLUDE_HEADERS :

 // the following http request headers should NOT have their values // returned for security reasons. private static final String[] EXCLUDE_HEADERS = { "Proxy-Authorization", "Authorization" }; 

That is why you have null on uc.getRequestProperty("Authorization") . Have you tried using HttpClient from Apache?

+3
source

Have you tried to subclass URLConnection or HttpURLConnection and override the getRequestProperty() method?

0
source

Source: https://habr.com/ru/post/891298/


All Articles