Я получаю сообщение об ошибке 'Текст JSONObject должен начинаться с' {'с 1 [символ 2, строка 1]'
при вызове NewsAPI с использованием RestTemplate of Spring.
Ниже приведен фрагмент кода, который я использовал для получения ответа. Я могу получить строку ответа, но не могу разобрать ее через класс org.JSON
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
public class APITest {
final private static String NEWSAPI_URI="https://newsapi.org/v2/top-headlines";
final private static String API_TOKEN_VAL=“*****************”;
final private static String API_TOKEN="apiKey";
final private static String COUNTYRY="Country";
final private static String COUNTYRY_VAL="US";
public static void main(String[] args) {
RestTemplate restTemplate=new RestTemplate();
UriComponentsBuilder builder=UriComponentsBuilder.fromHttpUrl(NEWSAPI_URI)
.queryParam(API_TOKEN, API_TOKEN_VAL)
.queryParam(COUNTYRY, COUNTYRY_VAL)
;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> responseEntity=restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
//parsing responseEntity
HttpStatus httpStatus=responseEntity.getStatusCode();
String responseString=responseEntity.getBody();
System.out.println(responseString);
if(httpStatus.is2xxSuccessful()) {
JSONObject jsonObject=new JSONObject(responseString.trim());
JSONArray articles=jsonObject.getJSONArray("articles");
//System.out.println(articles.getJSONObject(0).get("content"));
for(int it=0;it<articles.length();it++) {
JSONObject articleObject=articles.getJSONObject(it);
System.out.println(articleObject.getString("content"));
}
}
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}