调用高德地图API查询当天城市的气温信息

一、调用高德地图的API接口,查询当前城市(或者是任何城市)的天气情况,话不多说,直接上码。

要想调用API接口,首先得在高德地图API官网去生成自己的key,至于怎么生成也很简单,这里就不在描述了。

二、代码:

因为这里是后端代码,所以我将最后查询的信息写到一个类里面了,用于封装,最后以JSON的格式返回。

1、首先需要导入的依赖有:


            com.alibaba
            fastjson
            1.2.71
            compile
        
        
            com.squareup.okhttp3
            okhttp
            4.9.1
        

2、编写封装返回信息的实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class GaodeWeatherDTO {

    private String status;
    private String province;
    private String city;
    private String adcode;
    private String weather;
    private String temperature;
    private String humidity;    // 湿度

}

3、统一返回的JSON的风格,将信息的类信息也统一封装到对象中,几乎所有的类信息最后都以这个类来封装返回给前端:

public class BaseResponseDTO implements Serializable {

    @Setter
    @Getter
    private int code;       // 状态码

    @Setter
    @Getter
    private String message; // 返回消息体

}
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonPropertyOrder({"code","message","data"})
public class ApiRestResponseDTO extends BaseResponseDTO {

    private static final String SUCCESS_MESSAGE = "操作成功!";
    private T data;

    /**
     *
     * @param 
     * @return object return to client
     * 泛型方法中第一个  表示这个T是泛型,而不是具体的某一个类,第二个  代表返回值的类型
     */
    public static  ApiRestResponseDTO success(){
        ApiRestResponseDTO apiRestResponse = new ApiRestResponseDTO<>();
        // set 200 status at the http status
        apiRestResponse.setCode(HttpStatus.OK.value());
        // set default message
        apiRestResponse.setMessage(SUCCESS_MESSAGE);
        return apiRestResponse;
    }

    /**
     *
     * @param data
     * @param 
     * @return create a success response object with a default message
     */
    public static  ApiRestResponseDTO success(T data){
        ApiRestResponseDTO apiRestResponse = new ApiRestResponseDTO<>();
        // set 200 status at the http status
        apiRestResponse.setCode(HttpStatus.OK.value());
        // set default message
        apiRestResponse.setMessage(SUCCESS_MESSAGE);
        // set data
        apiRestResponse.setData(data);
        return apiRestResponse;
    }

    /**
     *
     * @param data
     * @param message
     * @param 
     * @return create a success response object with a customized message
     */
    public static  ApiRestResponseDTO success(T data, String message){
        ApiRestResponseDTO apiRestResponse = new ApiRestResponseDTO<>();
        // set 200 status at the http status
        apiRestResponse.setCode(HttpStatus.OK.value());
        // set default message
        apiRestResponse.setMessage(message);
        // set data
        apiRestResponse.setData(data);
        return apiRestResponse;
    }
}

4、编写OkHttp3的配置类

@Configuration
public class OkHttpConfig {

    @Bean
    public OkHttpClient initOkHttpClient(){
        return new OkHttpClient.Builder()
                .retryOnConnectionFailure(false)
                .connectionPool(new ConnectionPool(10000,10000, TimeUnit.MILLISECONDS))
                .connectTimeout(10000,TimeUnit.MILLISECONDS)
                .readTimeout(10000,TimeUnit.MILLISECONDS)
                .build();

    }
}

5、编写查询天气的方法,这里调用高德API(里面的key值可以写在yml或者properties配置文件中,灵活配置,)

public class GaoDeService{
/**
     *
     * @param adcode
     * @return 根据城市编码查询当天的天气,暂时不查看预报天气。
     */
    public GaodeWeatherDTO getCurrentWeather(String adcode) throws IOException {
        GaodeWeatherDTO weatherDTO = new GaodeWeatherDTO();
        HttpUrl url = HttpUrl.parse("https://restapi.amap.com/v3/weather/weatherInfo")
                .newBuilder()
                .addQueryParameter("Key",key)
                .addQueryParameter("extensions","base")
                .addQueryParameter("output","JSON")
                .addQueryParameter("city",adcode)
                .build();
        Request request = new Request.Builder().url(url).build();
        Response response = okHttpClient.newCall(request).execute();
        // 将json返回体转换为josn对象
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        // 从josn对象里面获取属性封装到GaodeWeatherDTO对象中去
        weatherDTO.setStatus(jsonObject.getString("status"));
        // JSON 对象是数组形式时
        JSONObject lives = jsonObject.getJSONArray("lives").getJSONObject(0);
        weatherDTO.setProvince(lives.getString("province"));
        weatherDTO.setCity(lives.getString("city"));
        weatherDTO.setAdcode(lives.getString("adcode"));
        weatherDTO.setTemperature(lives.getString("temperature"));
        weatherDTO.setWeather(lives.getString("weather"));
        weatherDTO.setHumidity(lives.getString("humidity"));
        return weatherDTO;
    }
}

上面代码忘了加key:

@Value("${gaode.key}")  // 从yml配置文件中获取这个key值
    private String key;

6、编写controller层,实现调用接口

@RestController
@RequestMapping("/maps/V1.0")
public class MapController {
/**
     *
     * @param adcode
     * @return 根据城市编码获取当前城市的温度
     * @throws IOException
     */
    @GetMapping("/weather")
    public ApiRestResponseDTO getWeather(@RequestParam String adcode) throws IOException {
        GaodeWeatherDTO currentWeather = gaodeTranService.getCurrentWeather(adcode);
        return  ApiRestResponseDTO.success(currentWeather);
    }
}

7、最后用postman测试一下:

调用高德地图API查询当天城市的气温信息_第1张图片

完美结束! 

你可能感兴趣的:(接口API,1024程序员节,java)