调用第三方接口

复制代码
利用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", "天气超时");
        }
    }
相关推荐
Zhou1411364 分钟前
SpringBoot_02_自动配置原理
java·spring boot·后端
FYKJ_201011 分钟前
SSM校园失物招领系统41452-计算机课程设计、毕业设计
java·vue.js·spring boot·python·mysql·typescript·spark
kv11014 分钟前
Android studio国内开发有关
java·数据库·android studio
卓怡学长40 分钟前
w198基于springboot始于足下健康打卡平台的设计与实现
java·spring boot·spring·intellij-idea
阿狗童鞋1 小时前
Java并发编程实战指南
java·开发语言
Joe_Wang51 小时前
【从0到1学习JVM · 15】对象在堆里来回倒腾,究竟怎样才会进老年代?
java·jvm·学习·垃圾回收
一条小小yu1 小时前
为什么使用springboot
java·spring boot·后端
Elastic 中国社区官方博客2 小时前
Kubernetes attributes processor v1:它对 EDOT Collector 意味着什么
java·大数据·elasticsearch·搜索引擎·贪心算法·kubernetes·全文检索
Sarvartha2 小时前
对象创建与引用
java·开发语言
大侠归来2 小时前
C语言与C++在基础语法上的区别
java·c语言·c++