getRequestProperty(“ Authorization”)始终返回null

getRequestProperty(“ Authorization”)始终返回null

如下

public class Main {
    public static void main(String[] args) throws IOException {
        URL url = new URL("http://example.com");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "Bearer your_token");
        connection.setRequestProperty("Authorization1", "Bearer your_token");
        // 获取请求头部信息
        String authHeader = connection.getRequestProperty("Authorization");
        String authHeader1 = connection.getRequestProperty("Authorization1");
        System.out.println("Authorization Header: " + authHeader);
        System.out.println("Authorization Header: " + authHeader1);
        // 处理响应等操作
        connection.connect();
        
    }
}

得到的结果为:

Authorization Header: null
Authorization Header: Bearer your_token

原因是: getRequestProperty这个方法

 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);
    }

该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"
   };

你可能感兴趣的:(java基础,java)