SpringBoot整合高德地圖天氣查詢的全過程
申請key
登錄高德,注冊,添加應(yīng)用,創(chuàng)建key
官網(wǎng)api:
https://lbs.amap.com/api/webservice/guide/api/weatherinfo
調(diào)用步驟:
第一步,申請”web服務(wù) API”密鑰(Key);
第二步,拼接HTTP請求URL,第一步申請的Key需作為必填參數(shù)一同發(fā)送;
第三步,接收HTTP請求返回的數(shù)據(jù)(JSON或XML格式),解析數(shù)據(jù)。
如無特殊聲明,接口的輸入?yún)?shù)和輸出數(shù)據(jù)編碼全部統(tǒng)一為UTF-8。
最主要的也是獲取到key

相關(guān)代碼
pom.xml
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
application.properties
server.port=2080 #The config for HttpClient http.maxTotal=300 http.defaultMaxPerRoute=50 http.connectTimeout=1000 http.connectionRequestTimeout=500 http.socketTimeout=5000 http.staleConnectionCheckEnabled=true gaode.key = 申請的key
HttpClientConfig
package com.zjy.map.config;
import lombok.Data;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;
import java.util.List;
@Data
@Configuration
@ConfigurationProperties(prefix = "http", ignoreUnknownFields = true)
public class HttpClientConfig {
private Integer maxTotal;// 最大連接
private Integer defaultMaxPerRoute;// 每個(gè)host的最大連接
private Integer connectTimeout;// 連接超時(shí)時(shí)間
private Integer connectionRequestTimeout;// 請求超時(shí)時(shí)間
private Integer socketTimeout;// 響應(yīng)超時(shí)時(shí)間
/**
* HttpClient連接池
* @return
*/
@Bean
public HttpClientConnectionManager httpClientConnectionManager() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(maxTotal);
connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
return connectionManager;
}
/**
* 注冊RequestConfig
* @return
*/
@Bean
public RequestConfig requestConfig() {
return RequestConfig.custom().setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout)
.build();
}
/**
* 注冊HttpClient
* @param manager
* @param config
* @return
*/
@Bean
public HttpClient httpClient(HttpClientConnectionManager manager, RequestConfig config) {
return HttpClientBuilder.create().setConnectionManager(manager).setDefaultRequestConfig(config)
.build();
}
@Bean
public ClientHttpRequestFactory requestFactory(HttpClient httpClient) {
return new HttpComponentsClientHttpRequestFactory(httpClient);
}
/**
* 使用HttpClient來初始化一個(gè)RestTemplate
* @param requestFactory
* @return
*/
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory) {
RestTemplate template = new RestTemplate(requestFactory);
List<HttpMessageConverter<?>> list = template.getMessageConverters();
for (HttpMessageConverter<?> mc : list) {
if (mc instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) mc).setDefaultCharset(Charset.forName("UTF-8"));
}
}
return template;
}
}
WeatherUtils
package com.zjy.map.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.net.URI;
import java.util.Map;
@Component
public class WeatherUtils {
/**日志對象*/
private static final Logger logger = LoggerFactory.getLogger(WeatherUtils.class);
@Value("${gaode.key}")
private String KEY;
public final String WEATHER_URL = "https://restapi.amap.com/v3/weather/weatherInfo?";
/**
* 發(fā)送get請求
* @return
*/
public JSONObject getCurrent(Map<String, String> params){
JSONObject jsonObject = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
// 創(chuàng)建URI對象,并且設(shè)置請求參數(shù)
try {
URI uri = getBuilderCurrent(WEATHER_URL, params);
// 創(chuàng)建http GET請求
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response = httpclient.execute(httpGet);
// 判斷返回狀態(tài)是否為200
jsonObject = getRouteCurrent(response);
httpclient.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* 根據(jù)不同的路徑規(guī)劃獲取距離
* @param response
* @return
*/
private static JSONObject getRouteCurrent(CloseableHttpResponse response) throws Exception{
JSONObject live = null;
// 判斷返回狀態(tài)是否為200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
logger.info("調(diào)用高德地圖接口返回的結(jié)果為:{}",content);
JSONObject jsonObject = (JSONObject) JSONObject.parse(content);
JSONArray lives = (JSONArray) jsonObject.get("lives");
live = (JSONObject) lives.get(0);
logger.info("返回的結(jié)果為:{}",JSONObject.toJSONString(live));
}
return live;
}
/**
* 封裝URI
* @param url
* @param params
* @return
* @throws Exception
*/
private URI getBuilderCurrent(String url, Map<String, String> params) throws Exception{
// 城市編碼,高德地圖提供
String adcode = params.get("adcode");
URIBuilder uriBuilder = new URIBuilder(url);
// 公共參數(shù)
uriBuilder.setParameter("key", KEY);
uriBuilder.setParameter("city", adcode);
logger.info("請求的參數(shù)key為:{}, cityCode為:{}", KEY, adcode);
URI uri = uriBuilder.build();
return uri;
}
/**
* 查詢未來的
* 發(fā)送get請求
* @return
*/
public JSONObject sendGetFuture(Map<String, String> params){
JSONObject jsonObject = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
// 創(chuàng)建URI對象,并且設(shè)置請求參數(shù)
try {
URI uri = getBuilderFuture(WEATHER_URL, params);
// 創(chuàng)建http GET請求
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response = httpclient.execute(httpGet);
// 判斷返回狀態(tài)是否為200
jsonObject = getRouteFuture(response);
httpclient.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* 封裝URI
* @param url
* @param params
* @return
* @throws Exception
*/
private URI getBuilderFuture(String url, Map<String, String> params) throws Exception{
// 城市編碼,高德地圖提供
String adcode = params.get("adcode");
URIBuilder uriBuilder = new URIBuilder(url);
// 公共參數(shù)
uriBuilder.setParameter("key", KEY);
uriBuilder.setParameter("city", adcode);
uriBuilder.setParameter("extensions", "all");
logger.info("請求的參數(shù)key為:{}, cityCode為:{}", KEY, adcode);
URI uri = uriBuilder.build();
return uri;
}
/**
* 根據(jù)不同的路徑規(guī)劃獲取距離
* @param response
* @return
*/
private static JSONObject getRouteFuture(CloseableHttpResponse response) throws Exception{
JSONObject live = null;
// 判斷返回狀態(tài)是否為200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
logger.info("調(diào)用高德地圖接口返回的結(jié)果為:{}",content);
JSONObject jsonObject = (JSONObject) JSONObject.parse(content);
JSONArray forecast = (JSONArray) jsonObject.get("forecasts");
live = (JSONObject) forecast.get(0);
logger.info("返回的結(jié)果為:{}",JSONObject.toJSONString(live));
}
return live;
}
}
WeatherController
package com.zjy.map.controller;
import com.alibaba.fastjson.JSONObject;
import com.zjy.map.utils.WeatherUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* 高德天氣
*/
@RestController
@RequestMapping("/weather")
public class WeatherController {
@Autowired
private WeatherUtils weatherUtils;
/**日志對象*/
private static final Logger logger = LoggerFactory.getLogger(WeatherController.class);
/**
* http://localhost:2080/weather/getCurrent?adcode=140200
* 獲取當(dāng)前的天氣預(yù)報(bào)
* @param adcode
* @return
*/
@GetMapping("/getCurrent")
public JSONObject getWeather(@RequestParam String adcode){
Map<String, String> params = new HashMap<>();
params.put("adcode", adcode);
logger.info("獲取當(dāng)前的天氣預(yù)報(bào),請求的參數(shù)為:{}", params);
JSONObject map = weatherUtils.getCurrent(params);
logger.info("獲取當(dāng)前的天氣預(yù)報(bào),返回的請求結(jié)果為:{}", map);
return map;
}
/**
* http://localhost:2080/weather/getFuture?adcode=140200
* 獲取未來的天氣預(yù)報(bào)
* @param adcode
* @return
*/
@GetMapping("/getFuture")
public JSONObject getFuture(@RequestParam String adcode){
Map<String, String> params = new HashMap<>();
params.put("adcode", adcode);
logger.info("獲取未來的天氣預(yù)報(bào),請求的參數(shù)為:{}", params);
JSONObject map = weatherUtils.sendGetFuture(params);
logger.info("獲取未來的天氣預(yù)報(bào),返回的請求結(jié)果為:{}", map);
return map;
}
}
代碼貼完了。開始測試
啟動(dòng)服務(wù)
城市編號
官網(wǎng)提供下載地址:
https://lbs.amap.com/api/webservice/download

這里獲取當(dāng)前時(shí)間的天氣情況與未來天氣情況返回?cái)?shù)據(jù)不一樣,所在寫了2個(gè)方法,參數(shù)只有一個(gè),城市編碼.
1.獲取當(dāng)前天氣
http://localhost:2080/weather/getCurrent?adcode=140200

2.獲取未來天氣
http://localhost:2080/weather/getFuture?adcode=140200

{
"province": "山西",
"casts": [
{
"date": "2021-12-13",
"dayweather": "晴",
"daywind": "西南",
"week": "1",
"daypower": "4",
"daytemp": "2",
"nightwind": "西南",
"nighttemp": "-18",
"nightweather": "晴",
"nightpower": "4"
},
{
"date": "2021-12-14",
"dayweather": "晴",
"daywind": "西",
"week": "2",
"daypower": "≤3",
"daytemp": "2",
"nightwind": "西",
"nighttemp": "-13",
"nightweather": "晴",
"nightpower": "≤3"
},
{
"date": "2021-12-15",
"dayweather": "多云",
"daywind": "西南",
"week": "3",
"daypower": "4",
"daytemp": "5",
"nightwind": "西南",
"nighttemp": "-12",
"nightweather": "多云",
"nightpower": "4"
},
{
"date": "2021-12-16",
"dayweather": "多云",
"daywind": "西北",
"week": "4",
"daypower": "4",
"daytemp": "-1",
"nightwind": "西北",
"nighttemp": "-18",
"nightweather": "晴",
"nightpower": "4"
}
],
"city": "大同市",
"adcode": "140200",
"reporttime": "2021-12-13 18:04:08"
}

測試OK!
總結(jié)
到此這篇關(guān)于SpringBoot整合高德地圖天氣查詢的文章就介紹到這了,更多相關(guān)SpringBoot整合高德地圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java編程中字節(jié)流轉(zhuǎn)換成字符流的實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄猨ava編程中字節(jié)流轉(zhuǎn)換成字符流的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01
IDEA如何自動(dòng)生成serialVersionUID的設(shè)置
這篇文章主要介紹了IDEA如何自動(dòng)生成 serialVersionUID 的設(shè)置,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
idea 在springboot中使用lombok插件的方法
這篇文章主要介紹了idea 在springboot中使用lombok的相關(guān)資料,通過代碼給大家介紹在pom.xml中引入依賴的方法,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-08-08
Java 微信公眾號開發(fā)相關(guān)總結(jié)
公眾號作為主流的自媒體平臺,有著不少人使用。這次以文本回復(fù)作為案例來講解Java相關(guān)的微信公眾號開發(fā)2021-05-05
基于SpringBoot和Vue實(shí)現(xiàn)頭像上傳與回顯功能
在現(xiàn)代Web應(yīng)用中,用戶個(gè)性化體驗(yàn)尤為重要,其中頭像上傳與回顯是一個(gè)常見的功能需求,本文將詳細(xì)介紹如何使用Spring Boot和Vue.js構(gòu)建一個(gè)前后端協(xié)同工作的頭像上傳系統(tǒng),并實(shí)現(xiàn)圖片的即時(shí)回顯,需要的朋友可以參考下2024-08-08
JVM優(yōu)先級線程池做任務(wù)隊(duì)列的實(shí)現(xiàn)方法
這篇文章主要介紹了JVM優(yōu)先級線程池做任務(wù)隊(duì)列的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
Springcould多模塊搭建Eureka服務(wù)器端口過程詳解
這篇文章主要介紹了Springcould多模塊搭建Eureka服務(wù)器端口過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
Java之SpringBoot集成ActiveMQ消息中間件案例講解
這篇文章主要介紹了Java之SpringBoot集成ActiveMQ消息中間件案例講解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
Java Chassis3過載狀態(tài)下的快速失敗解決分析
本文解密了Java Chassis 3快速失敗相關(guān)的機(jī)制和背后故事,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01

