调用第三方接口

复制代码
利用OkHttp调用第三方天气接口

1.获取第三方接口api

复制代码
private final String WEATHER_API_URL = "https://cn.apihz.cn/api/tianqi/tqybbaiducn.php?id="+id+"&key="+id+"&sheng=省份&place=城市";

2.创建OkHttpclient对象

复制代码
private final OkHttpClient client = new OkHttpClient();

3.返回结果

复制代码
public Map<String, String> getWeatherAnePm() throws Exception {
    Map<String, String> weatherAndPm = new HashMap<>();
    // 天气请求
    Request request = new Request.Builder().url(WEATHER_API_URL).build();
    try (Response response = client.newCall(request).execute()) {
        if (response.isSuccessful()) {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response.body().string());
            String weather = String.valueOf(jsonNode.get("result").get("now").get("temp"));
            weatherAndPm.put("weather", weather);
        } else {
            weatherAndPm.put("weather", "天气超时");
        }
    }
相关推荐
YA33316 分钟前
java设计模式二、工厂
java·开发语言·设计模式
金色天际线-23 分钟前
Nginx 优化与防盗链配置指南
java·后端·spring
我爱挣钱我也要早睡!1 小时前
Java 复习笔记
java·开发语言·笔记
AD钙奶-lalala3 小时前
Mac OS上搭建 http server
java
皮皮林5517 小时前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
weixin_456904277 小时前
Spring Boot 用户管理系统
java·spring boot·后端
趁你还年轻_7 小时前
异步编程CompletionService
java
DKPT7 小时前
Java内存区域与内存溢出
java·开发语言·jvm·笔记·学习
sibylyue8 小时前
Guava中常用的工具类
java·guava
奔跑吧邓邓子8 小时前
【Java实战㉞】从0到1:Spring Boot Web开发与接口设计实战
java·spring boot·实战·web开发·接口设计