gpt4 book ai didi

java - 如何使用 REST Api,然后将热门故事显示为 JSON

转载 作者:行者123 更新时间:2023-12-02 01:30:12 29 4
gpt4 key购买 nike

目标:创建一个 Spring Boot 项目来使用《纽约时报》的公共(public) API 来显示当前的头条新闻。

我所做的:我已经使用了 REST Api 并将我的响应存储到 jsonObject 中。我尝试通过两个单元测试,但无法通过第一个单元测试。尽管我通过了第二个 junit 测试,但很确定我所做的事情是不正确的。

新闻POJO

public class News {

private String title;
private String section;

// GETTER & SETTER

}

新闻服务类

@Service public class NewsService {

private String apiKey = "gIIWu7P82GBslJAd0MUSbKMrOaqHjWOo";

public News getTopStories() throws Exception {


RestTemplate restTemplate = new RestTemplate();
News news = new News();

String getUrl = "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=" + apiKey;

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<Map> newsList = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Map.class);
JSONObject jsonObject;

if (newsList.getStatusCode() == HttpStatus.OK) {

jsonObject = new JSONObject(newsList.getBody());
JSONArray jsonArray = jsonObject.getJSONArray("results");

for(int i=0; i<jsonArray.length(); i++) {

news.setTitle(jsonArray.getJSONObject(i).get("title").toString());
news.setSection(jsonArray.getJSONObject(i).get("section").toString());

}
}
// this is only returning the last index of the jsonArray (pretty sure I am suppose to return all to in my URL). Can't seem to come up with the logic to do that.
return news;
}

}

新闻 Controller 类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class NewsController {

@Autowired
NewsService newsService;

@RequestMapping(value = "/news/topstories", method = RequestMethod.GET)
public News getNews() throws Exception {
return newsService.getTopStories();
}

}

需要通过 JUnit 测试

@Test
public void retrievetest_ok() throws Exception {

mockMvc.perform(get("/api/news/topstories" )).andDo(print())
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.results.[0].title").exists())
.andExpect(MockMvcResultMatchers.jsonPath("$.section").exists());


}

@Test public void Newstest_ok() throws Exception {
mockMvc.perform(get("/api/news/topstories" ))
.andDo(print())
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.title").exists())
.andExpect(MockMvcResultMatchers.jsonPath("$.section").exists());
}


}

我在第一次 JUnit 测试时收到错误

MockHttpServletRequest:
HTTP Method = GET
Request URI = /api/news/topstories
Parameters = {}
Headers = {}

Handler:
Type = com.example.project.NewsController
Method = public com.example.project.News com.example.project.NewsController.getNews() throws java.lang.Exception

Async:
Async started = false
Async result = null

Resolved Exception:
Type = null

ModelAndView:
View name = null
View = null
Model = null

FlashMap:
Attributes = null


MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"title":"Shrinking and Quaking Hint at Moon’s Tectonic Life","section":"Science"}
Forwarded URL = null
Redirected URL = null
Cookies = []

java.lang.AssertionError: No value at JSON path "$.results.[0].title", exception: Missing property in path $['results']
...
...
...
...

最佳答案

需要更新 POJO 才能通过所有测试用例。

public class News{
private String section;
private Results[] results;
private String title;


public Results[] getResults() {
return results;
}

public void setResults(Results[] results) {
this.results = results;
}

public String getSection() {
return section;
}

public void setSection(String section) {
this.section = section;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

}

然后您需要再添加一个名为 Result 的 POJO 类

public class Results{
private String title;

public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

最后是服务类

public News getTopStories()
{
List<News> topStories = new ArrayList<>();
RestTemplate restTemplate = new RestTemplate();
String getUrl = "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=<your-api-key>";
News news=new News();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<Map> newsList = restTemplate.exchange(getUrl, HttpMethod.GET, entity, Map.class);
JSONObject jsonObject;

if (newsList.getStatusCode() == HttpStatus.OK) {

jsonObject = new JSONObject(newsList.getBody());
JSONArray jsonArray = jsonObject.getJSONArray("results");
Results[] results = new Results[jsonArray.length()];
for(int i=0; i<jsonArray.length(); i++) {
news.setTitle(jsonArray.getJSONObject(i).get("title").toString());
news.setSection(jsonArray.getJSONObject(i).get("section").toString());
String title=jsonArray.getJSONObject(i).get("title").toString();
results[i]=new Results();
results[i].setTitle(title);
news.setResults(results);
topStories.add(news);
}

}
return topStories.get(0);
}

这肯定适用于您提到的所有 JUnit。或者您甚至可以创建内部类 Result 而不是创建新的 POJO 文件。

关于java - 如何使用 REST Api,然后将热门故事显示为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56211522/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com