java—希望通过url使用api键和必需参数检索json数据体,但不起作用

brccelvz  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(176)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

5天前关门了。
改进这个问题
我使用springboot运行程序,并通过responseentity变量收集json数据。我使用url和string类作为给定参数,通过restemplate变量访问它。我稍后使用gson将数据存储为json对象,该对象稍后将转换为java对象用于数据存储。我现在的问题是,当访问指定的端点以引入访问外部api所需的参数时,localhost页上出现“404错误”,我不确定哪里出错了。
代码示例
代码片段如下所示:

//Create RequestMapping for a HTTP GET request to a weather API(Using OpenWeatherMap API)
@RequestMapping("/city")
public Weather getWeather(@RequestParam(value="city", defaultValue = "Houston")String city)
{
    //Use this url to retreive the data 
    String url = "api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + currentWeatherAPIKey;

    /* ResponseEntity helps return the whole Http Response into the ResponseEntity Object
    This includes the headers, body, and status-.
    We're going to retreive the body of the weather data for now. 
    */

    ResponseEntity<String> weather = restTemplate.getForEntity("api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + currentWeatherAPIKey, String.class);

    //Get the status code 
    String statuscode = weather.getStatusCode().toString();
    logger.info("The status code is " + statuscode);

    //Use Json to get data and store in the Pokemon class using gson
    JsonObject jsonResult = gson.fromJson(weather.getBody(), JsonObject.class);

    //Create a json object to store data for the specific json array "weather" 
    JsonObject weatherdata = jsonResult.getAsJsonArray("weather").getAsJsonObject();

    //Create a json object to store data for the specific json object "main"
    JsonObject temperaturedata = jsonResult.getAsJsonObject("main");

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题