- 新建数据接收实体类
package com.komlin.common.pojo.dto;
/**
* @author mt
*/
@lombok.Data
public class WeatherDTO {
private Data data;
private int status;
private String desc;
}
- 编写获取天气工具类
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());
}
}
以下是返回数据详解: