欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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)文章

  • mybatis?plus?MetaObjectHandler?不生效的解決

    mybatis?plus?MetaObjectHandler?不生效的解決

    今天使用mybatis-plus自動(dòng)為更新和插入操作插入更新時(shí)間和插入時(shí)間,配置了MetaObjectHandler不生效,本文就來(lái)解決一下,具有一定的 參考價(jià)值,感興趣的可以了解一下
    2023-10-10
  • java局域網(wǎng)聊天小程序

    java局域網(wǎng)聊天小程序

    這篇文章主要為大家詳細(xì)介紹了java局域網(wǎng)聊天小程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • Spring MVC溫故而知新系列教程之請(qǐng)求映射RequestMapping注解

    Spring MVC溫故而知新系列教程之請(qǐng)求映射RequestMapping注解

    這篇文章主要介紹了Spring MVC溫故而知新系列教程之請(qǐng)求映射RequestMapping注解的相關(guān)知識(shí),文中給大家介紹了RequestMapping注解提供的幾個(gè)屬性及注解說(shuō)明,感興趣的朋友跟隨腳本之家小編一起學(xué)習(xí)吧
    2018-05-05
  • Java事務(wù)的個(gè)人理解小結(jié)

    Java事務(wù)的個(gè)人理解小結(jié)

    數(shù)據(jù)庫(kù)操作的事務(wù)習(xí)慣上就稱為Java事務(wù)
    2013-03-03
  • Java中的static關(guān)鍵字全面解析

    Java中的static關(guān)鍵字全面解析

    這篇文章主要介紹了Java中的static關(guān)鍵字全面解析的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-06-06
  • Spring?Cloud?Gateway動(dòng)態(tài)路由Apollo實(shí)現(xiàn)詳解

    Spring?Cloud?Gateway動(dòng)態(tài)路由Apollo實(shí)現(xiàn)詳解

    這篇文章主要為大家介紹了Spring?Cloud?Gateway動(dòng)態(tài)路由通過(guò)Apollo實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-10-10
  • java中g(shù)c算法實(shí)例用法

    java中g(shù)c算法實(shí)例用法

    在本篇文章里小編給大家整理了一篇關(guān)于java中g(shù)c算法實(shí)例用法,有興趣的朋友們可以參考學(xué)習(xí)下。
    2021-01-01
  • java單機(jī)接口限流處理方案詳解

    java單機(jī)接口限流處理方案詳解

    這篇文章主要為大家詳細(xì)介紹了java單機(jī)接口限流處理方案,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • Mybatis plus通用字段自動(dòng)填充的示例

    Mybatis plus通用字段自動(dòng)填充的示例

    這篇文章主要介紹了Mybatis plus通用字段自動(dòng)填充的示例,幫助大家更好的理解和使用Mybatis,感興趣的朋友可以了解下
    2021-01-01
  • Java中使用print、printf、println的示例及區(qū)別

    Java中使用print、printf、println的示例及區(qū)別

    Java?的輸出方式一般有這三種,print、println、printf,它們都是?java.long?包里的System類中的方法,本文重點(diǎn)給大家介紹Java中使用print、printf、println的示例,需要的朋友可以參考下
    2023-05-05

最新評(píng)論