最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合高德地圖天氣查詢的全過(guò)程

 更新時(shí)間:2021年12月15日 10:30:38   作者:DY丶老周  
這篇文章主要給大家介紹了關(guān)于SpringBoot整合高德地圖天氣查詢的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用springboot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

申請(qǐng)key

登錄高德,注冊(cè),添加應(yīng)用,創(chuàng)建key

官網(wǎng)api:

https://lbs.amap.com/api/webservice/guide/api/weatherinfo

調(diào)用步驟:

第一步,申請(qǐng)”web服務(wù) API”密鑰(Key);

第二步,拼接HTTP請(qǐng)求URL,第一步申請(qǐng)的Key需作為必填參數(shù)一同發(fā)送;

第三步,接收HTTP請(qǐng)求返回的數(shù)據(jù)(JSON或XML格式),解析數(shù)據(jù)。

如無(wú)特殊聲明,接口的輸入?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 = 申請(qǐng)的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;// 請(qǐng)求超時(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;
    }

    /**
     * 注冊(cè)RequestConfig
     * @return
     */
    @Bean
    public RequestConfig requestConfig() {
        return RequestConfig.custom().setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout)
                .build();
    }

    /**
     * 注冊(cè)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來(lái)初始化一個(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 {

    /**日志對(duì)象*/
    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請(qǐng)求
     * @return
     */
    public JSONObject getCurrent(Map<String, String> params){

        JSONObject jsonObject = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 創(chuàng)建URI對(duì)象,并且設(shè)置請(qǐng)求參數(shù)
        try {
            URI uri = getBuilderCurrent(WEATHER_URL, params);
            // 創(chuàng)建http GET請(qǐng)求
            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("請(qǐng)求的參數(shù)key為:{}, cityCode為:{}", KEY, adcode);
        URI uri = uriBuilder.build();
        return uri;
    }

    /**
     * 查詢未來(lái)的
     * 發(fā)送get請(qǐng)求
     * @return
     */
    public JSONObject sendGetFuture(Map<String, String> params){

        JSONObject jsonObject = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 創(chuàng)建URI對(duì)象,并且設(shè)置請(qǐng)求參數(shù)
        try {
            URI uri = getBuilderFuture(WEATHER_URL, params);
            // 創(chuàng)建http GET請(qǐng)求
            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("請(qǐng)求的參數(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;

    /**日志對(duì)象*/
    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),請(qǐng)求的參數(shù)為:{}", params);
        JSONObject map = weatherUtils.getCurrent(params);
        logger.info("獲取當(dāng)前的天氣預(yù)報(bào),返回的請(qǐng)求結(jié)果為:{}", map);
        return map;
    }

    /**
     * http://localhost:2080/weather/getFuture?adcode=140200
     * 獲取未來(lái)的天氣預(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("獲取未來(lái)的天氣預(yù)報(bào),請(qǐng)求的參數(shù)為:{}", params);
        JSONObject map = weatherUtils.sendGetFuture(params);
        logger.info("獲取未來(lái)的天氣預(yù)報(bào),返回的請(qǐng)求結(jié)果為:{}", map);
        return map;
    }
}

代碼貼完了。開(kāi)始測(cè)試

啟動(dòng)服務(wù)

城市編號(hào)

官網(wǎng)提供下載地址:

https://lbs.amap.com/api/webservice/download

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

1.獲取當(dāng)前天氣

http://localhost:2080/weather/getCurrent?adcode=140200

2.獲取未來(lái)天氣

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"
}

測(cè)試OK!

總結(jié)

到此這篇關(guān)于SpringBoot整合高德地圖天氣查詢的文章就介紹到這了,更多相關(guān)SpringBoot整合高德地圖內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java編程中字節(jié)流轉(zhuǎn)換成字符流的實(shí)現(xiàn)方法

    java編程中字節(jié)流轉(zhuǎn)換成字符流的實(shí)現(xiàn)方法

    下面小編就為大家?guī)?lái)一篇java編程中字節(jié)流轉(zhuǎn)換成字符流的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-01-01
  • 若依前后端打成一個(gè)JAR包部署的完整步驟

    若依前后端打成一個(gè)JAR包部署的完整步驟

    這篇文章主要介紹了如何將若依前后端分離項(xiàng)目打包成jar,不使用nginx轉(zhuǎn)發(fā),前端修改了路由模式和環(huán)境變量配置,后端增加了依賴、配置了Thymeleaf和訪問(wèn)路徑,需要的朋友可以參考下
    2025-01-01
  • IDEA如何自動(dòng)生成serialVersionUID的設(shè)置

    IDEA如何自動(dòng)生成serialVersionUID的設(shè)置

    這篇文章主要介紹了IDEA如何自動(dòng)生成 serialVersionUID 的設(shè)置,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • idea 在springboot中使用lombok插件的方法

    idea 在springboot中使用lombok插件的方法

    這篇文章主要介紹了idea 在springboot中使用lombok的相關(guān)資料,通過(guò)代碼給大家介紹在pom.xml中引入依賴的方法,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2021-08-08
  • Java 微信公眾號(hào)開(kāi)發(fā)相關(guān)總結(jié)

    Java 微信公眾號(hào)開(kāi)發(fā)相關(guān)總結(jié)

    公眾號(hào)作為主流的自媒體平臺(tái),有著不少人使用。這次以文本回復(fù)作為案例來(lái)講解Java相關(guān)的微信公眾號(hào)開(kāi)發(fā)
    2021-05-05
  • 基于SpringBoot和Vue實(shí)現(xiàn)頭像上傳與回顯功能

    基于SpringBoot和Vue實(shí)現(xiàn)頭像上傳與回顯功能

    在現(xiàn)代Web應(yīng)用中,用戶個(gè)性化體驗(yàn)尤為重要,其中頭像上傳與回顯是一個(gè)常見(jiàn)的功能需求,本文將詳細(xì)介紹如何使用Spring Boot和Vue.js構(gòu)建一個(gè)前后端協(xié)同工作的頭像上傳系統(tǒng),并實(shí)現(xiàn)圖片的即時(shí)回顯,需要的朋友可以參考下
    2024-08-08
  • JVM優(yōu)先級(jí)線程池做任務(wù)隊(duì)列的實(shí)現(xiàn)方法

    JVM優(yōu)先級(jí)線程池做任務(wù)隊(duì)列的實(shí)現(xiàn)方法

    這篇文章主要介紹了JVM優(yōu)先級(jí)線程池做任務(wù)隊(duì)列的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Springcould多模塊搭建Eureka服務(wù)器端口過(guò)程詳解

    Springcould多模塊搭建Eureka服務(wù)器端口過(guò)程詳解

    這篇文章主要介紹了Springcould多模塊搭建Eureka服務(wù)器端口過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • Java之SpringBoot集成ActiveMQ消息中間件案例講解

    Java之SpringBoot集成ActiveMQ消息中間件案例講解

    這篇文章主要介紹了Java之SpringBoot集成ActiveMQ消息中間件案例講解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-07-07
  • Java Chassis3過(guò)載狀態(tài)下的快速失敗解決分析

    Java Chassis3過(guò)載狀態(tài)下的快速失敗解決分析

    本文解密了Java Chassis 3快速失敗相關(guān)的機(jī)制和背后故事,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01

最新評(píng)論

南雄市| 延庆县| 甘德县| 福安市| 黎川县| 岢岚县| 沁源县| 三穗县| 伊宁市| 勐海县| 剑川县| 乃东县| 密云县| 双城市| 上蔡县| 慈利县| 崇左市| 乐山市| 温泉县| 秭归县| 西充县| 开鲁县| 洪洞县| 日土县| 旌德县| 博湖县| 华安县| 博罗县| 兴和县| 遂川县| 基隆市| 石门县| 定日县| 承德县| 都安| 冷水江市| 盘锦市| 拜城县| 宜春市| 台中市| 甘南县|