【发布时间】:2022-01-23 15:42:49
【问题描述】:
在 Http 请求、json 等方面,我是一个完整的初学者。我正在尝试通过 Java 的 HttpClient 和 HttpRequest 访问食物数据。数据包含很多信息,但我只想显示“描述”。这是我的美食课:
public class Food {
String description;
}
还有我的要求:
public class Test {
public static void main(String[] args) throws IOException, InterruptedException {
// create a client
HttpClient client = HttpClient.newHttpClient();
// create a request
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(
URI.create("https://api.nal.usda.gov/fdc/v1/foods/search?query=mango&pageSize=1&pageNumber=1&api_key=...")
).build();
// use the client to send the request
HttpResponse<String> response = client.send(request,HttpResponse.BodyHandlers.ofString());
Food food = new Gson().fromJson(response.body(), Food.class);
// the response:
System.out.println(response.body());
System.out.println(food.description);
}
}
现在第一个打印语句给了我所有的数据:
{"totalHits":11,"currentPage":1,"totalPages":11,"pageList":[1,2,3,4,5,6,7,8,9,10],"foodSearchCriteria":{"dataType":["Survey (FNDDS)"],"query":"mango","generalSearchInput":"mango","pageNumber":1,"numberOfResultsPerPage":50,"pageSize":1,"requireAllWords":false,"foodTypes":["Survey (FNDDS)"]},"foods":[{"fdcId":1102670,"description":"Mango, raw","lowercaseDescription"
这还不是全部,但您可以在所有数据的这一部分末尾找到描述部分。问题是第二个打印语句不打印描述,它打印空。出了什么问题? Api 文档:https://fdc.nal.usda.gov/api-spec/fdc_api.html#/
【问题讨论】:
标签: java json gson httprequest httpclient