【问题标题】:how to resolve 'HttpHeaders' has private access in 'org.apache.http.HttpHeaders' error如何解决 'HttpHeaders' 在 'org.apache.http.HttpHeaders' 错误中具有私有访问权限
【发布时间】:2018-11-29 18:51:21
【问题描述】:

我正在尝试使用 RestTemplate 发出 Http 请求,但它不断给我错误:'HttpHeaders' has private access in 'org.apache.http.HttpHeaders'

我只是想写这行:

HttpHeaders headers = new HttpHeaders();

【问题讨论】:

  • 你打算如何在你的代码中使用这个对象?请注意,org.apache.http.HttpHeaders 只不过是一组常量。

标签: java spring-boot gradle header http-headers


【解决方案1】:

包名错误,为了在使用Spring restTemplate时添加headers,你应该使用org.springframework.http.HttpHeaders.HttpHeaders而不是org.apache.http.HttpHeaders。 以下是添加请求头的代码sn-p。

// request resource
HttpHeaders headers = new HttpHeaders();
headers.set("headerName", "headerValue");

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<String> response = restTemplate.exchange("https://example.com", HttpMethod.GET, entity, String.class);

【讨论】:

    【解决方案2】:

    org.apache.http.HttpHeaders 中的构造函数是私有构造函数 - 参见源代码克隆 {here}。由于您正在尝试调用私有属性,因此该错误消息是预期的。

    附上相关代码sn-p供后人参考:

    public final class HttpHeaders {
    
        private HttpHeaders() {
        }
    
        // ....
        // bunch of defined constants
        // ....
    }
    

    这个类背后的基本原理在类文档字符串中指定,

    /**
     * Constants enumerating the HTTP headers. All headers defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and RFC2518
     * (WebDAV) are listed.
     *
     * @since 4.1
     */
    

    这不是您要在这里实现的目标。如果您希望使用 apache 库发出包含标头的请求的远程请求,请关注 {this example}。为后人添加相关代码sn-p:

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(SAMPLE_URL);
    request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    client.execute(request);
    

    如果您使用 >=4.3 的 HttpClient,您可能需要执行以下操作:

    HttpUriRequest request = RequestBuilder.get()
      .setUri(SAMPLE_URL)
      .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
      .build();
    

    【讨论】:

    • 请不要链接到非官方文档的外部资源。链接可能会消失,使答案变得毫无价值。最好找到提供类似信息的 StackOverflow 答案或在答案中提供简短示例。
    • 啊,好点@RealSkeptic。这在过去肯定让我感到痛苦。让我更新:)
    猜你喜欢
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 2013-10-27
    • 2023-03-23
    • 2014-11-24
    • 1970-01-01
    相关资源
    最近更新 更多