java根据城市得到当前天气或近一周天气

  1. 新建数据接收实体类
package com.komlin.common.pojo.dto;

/**
 * @author mt
 */
@lombok.Data
public class WeatherDTO {
    private Data data;
    private int status;
    private String desc;
}
  1. 编写获取天气工具类
package com.komlin.project.module.weather.util;

import com.alibaba.fastjson.JSONObject;
import com.komlin.common.pojo.dto.WeatherDTO;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import java.io.IOException;

/**
 * Created by mt on 2020-08-21
 */
public class WeatherUtils {

    private static OkHttpClient httpClient = new OkHttpClient();

    /**
     * 通过城市名称获取该城市的天气信息
     * @param cityName
     * @return
     */
    public static String GetWeatherDate(String cityName) {
        String weather_url = "http://wthrcdn.etouch.cn/weather_mini?city=" + cityName;
        return httpGet(weather_url);
    }

    /**
     * okhttp get请求
     * @param url
     * @return
     */
    private static String httpGet(String url){
        String body = null;
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = httpClient.newCall(request);
        try {
            body = call.execute().body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    /**
     * 将json格式数据进行解析,返回一个WeatherDTO对象
     * @param weatherInfoByJson
     * @return
     */
    public static WeatherDTO getWeather(String weatherInfoByJson){
        return JSONObject.parseObject(weatherInfoByJson, WeatherDTO.class);
    }

    public static void main(String[] args) {
        String info = WeatherUtils.GetWeatherDate("南阳");
        WeatherDTO weather = getWeather(info);
        System.out.println(weather.toString());
    }
}

以下是返回数据详解:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值