Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to resolve 'HttpHeaders' has private access in 'org.apache.http.HttpHeaders' error

I am trying to make an Http Request using RestTemplate, and it keeps on giving me the error: 'HttpHeaders' has private access in 'org.apache.http.HttpHeaders'

I am simply trying to write this line:

HttpHeaders headers = new HttpHeaders();
like image 825
Brian Akumah Avatar asked Jun 20 '18 15:06

Brian Akumah


2 Answers

The package name is wrong, in order to add headers when using Spring restTemplate, you should use org.springframework.http.HttpHeaders.HttpHeaders instead of org.apache.http.HttpHeaders. The following is the code snippet that adds request headers.

// 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);
like image 51
chao_chang Avatar answered Oct 13 '22 23:10

chao_chang


The constructor in org.apache.http.HttpHeaders is a private constructor - see source code clone {here}. Since you are trying to invoke a private attribute, that error message is expected.

Attaching relevant code snippet for posterity:

public final class HttpHeaders {

    private HttpHeaders() {
    }

    // ....
    // bunch of defined constants
    // ....
}

The rationale behind this class is specified in the class docstring,

/**
 * 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
 */

which is not the what you are trying to achieve here. If you wish to make a remote request, using apache library, with a request that contains headers, please follow {this example}. Adding relevant code snippet for posterity:

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

If you are using >=4.3 of HttpClient, you would want to do something like this:

HttpUriRequest request = RequestBuilder.get()
  .setUri(SAMPLE_URL)
  .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  .build();
like image 1
Debosmit Ray Avatar answered Oct 14 '22 00:10

Debosmit Ray