- 新建数据接收实体类
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());
}
}
以下是返回数据详解:

本文详细介绍了一种使用Java实现的城市天气信息查询的方法。通过创建WeatherDTO数据接收实体类,配合OkHttp进行HTTP请求,从etouch.cn获取天气数据,并利用FastJSON解析返回的JSON格式天气信息。文章提供了完整的代码示例,包括如何发送GET请求、解析响应数据及运行结果。
872

被折叠的 条评论
为什么被折叠?



