我正在尝试使用Spring RestTemplate获取Twitter推文。我的代码如下:
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());
}
我收到以下错误:
线程中的异常&#34; main&#34; org.springframework.web.client.HttpClientErrorException:401 需要授权 org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) 在 org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641) 在 org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597) 在 org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557) 在 org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475) 在 com.lftechnology.amlf.screening.service.impl.BalanceMediaSearchResultServiceImpl.main(BalanceMediaSearchResultServiceImpl.java:202)
答案 0 :(得分:6)
您似乎在标题中设置了错误的参数。试试这个:
httpHeaders.set("Authorization","Bearer " + accessToken);
注意Bearer之后的空间很重要。