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();
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);
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With