http://www.importnew.com/27014.html
public class WeatherResponse implements Serializable { private static final long serialVersionUID = 1L; private Weather data; // 消息数据 private String status; // 消息状态 private String desc; // 消息描述 public Weather getData() { return data; } public void setData(Weather data) { this.data = data; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
接口:
public interface WeatherDataService { /** * 根据城市ID查询天气数据 * @param cityId * @return */ WeatherResponse getDataByCityId(String cityId); /** * 根据城市名称查询天气数据 * @param cityId * @return */ WeatherResponse getDataByCityName(String cityName); }
实现:
@Service public class WeatherDataServiceImpl implements WeatherDataService { @Autowired private RestTemplate restTemplate; private final String WEATHER_API = "http://wthrcdn.etouch.cn/weather_mini"; @Override public WeatherResponse getDataByCityId(String cityId) { String uri = WEATHER_API + "?citykey=" + cityId; return this.doGetWeatherData(uri); } @Override public WeatherResponse getDataByCityName(String cityName) { String uri = WEATHER_API + "?city=" + cityName; return this.doGetWeatherData(uri); } private WeatherResponse doGetWeatherData(String uri) { ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class); String strBody = null; if (response.getStatusCodeValue() == 200) { strBody = response.getBody(); } ObjectMapper mapper = new ObjectMapper(); WeatherResponse weather = null; try { weather = mapper.readValue(strBody, WeatherResponse.class); } catch (IOException e) { e.printStackTrace(); } return weather; } }
控制器:
@RestController @RequestMapping("/weather") public class WeatherController { @Autowired private WeatherDataService weatherDataService; @GetMapping("/cityId/{cityId}") public WeatherResponse getReportByCityId(@PathVariable("cityId") String cityId) { return weatherDataService.getDataByCityId(cityId); } @GetMapping("/cityName/{cityName}") public WeatherResponse getReportByCityName(@PathVariable("cityName") String cityName) { return weatherDataService.getDataByCityName(cityName); } }