Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestTemplate gives 401 Authorization Required while getting data from Twitter

I am trying to get twitter tweets using Spring RestTemplate. My code is below:

    public static void main(String[] args) {

    RestTemplate restTemplate = new RestTemplate();

    org.springframework.http.HttpHeaders httpHeaders = new org.springframework.http.HttpHeaders();

    String url = "https://api.twitter.com/1.1/search/tweets.json q=java";        
    String headerName = "Authorization";
    String headerValue = OAUTH_PARAMETERS
    httpHeaders.add(headerName, headerValue);
    httpHeaders.add("Content-Type", "application/json");
    HttpEntity<String> requestEntity = new HttpEntity<>("Headers", httpHeaders);
    System.out.println(">>>>>>>" + restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class).getBody());
}

I am getting following errors:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 Authorization Required at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557) at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475) at com.lftechnology.amlf.screening.service.impl.BalanceMediaSearchResultServiceImpl.main(BalanceMediaSearchResultServiceImpl.java:202)

like image 466
Kiran Pariyar Avatar asked Mar 14 '16 04:03

Kiran Pariyar


1 Answers

It appears that you are setting wrong parameters in the header. Try this:

httpHeaders.set("Authorization","Bearer " + accessToken);

notice that the space after Bearer is important.

like image 126
Mukul Tripathi Avatar answered Nov 15 '22 03:11

Mukul Tripathi