Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting custom HTTP request headers in an URL object doesn't work

I am trying to fetch an image from an IP camera using HTTP. The camera requires HTTP basic authentication, so I have to add the corresponding 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 am later passing the url object to ImageIO.read(), and, as you can guess, I am getting an HTTP 401 Unauthorized, although user and pass are correct.

What am I doing wrong?

I've also tried new URL("http://user:pass@myipcam/snapshot.jpg"), but that doesn't work either.

like image 550
Blagovest Buyukliev Avatar asked Jun 24 '11 14:06

Blagovest Buyukliev


2 Answers

In class sun.net.www.protocol.http.HttpURLConnection, which extends java.net.HttpURLConnection, the following method getRequestProperty(String key) was overridden to return null when requesting security 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 declaration 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's why you're having a null on uc.getRequestProperty("Authorization"). Have you tried using HttpClient from Apache?

like image 158
Buhake Sindi Avatar answered Sep 29 '22 13:09

Buhake Sindi


Issue resolved. It didn't work because I was passing url to ImageIO.read().

Instead, passing uc.getInputStream() got it working.

like image 35
Blagovest Buyukliev Avatar answered Sep 29 '22 12:09

Blagovest Buyukliev