首页 > 其他分享 >根据用户的请求ip地址获取天气(对接高德地图api)

根据用户的请求ip地址获取天气(对接高德地图api)

时间:2022-10-29 10:11:36浏览次数:83  
标签:String getString api ip request weatherDTO weather 高德

1、获取请求的ip地址(高德地图api)

package com.yami.shop.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.*;

import java.net.InetAddress;

@Slf4j
public class IpInfoUtil {


    public static String getIpAddr(HttpServletRequest request) throws SocketException {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if(ip != null) {
            ip=ip.split(",")[0];
        }
        return ip;
        /*String ip = "http://pv.sohu.com/cityjson?ie=utf-8";
        String inputLine = "";
        String read = "";
        String toIp = "";
        try {
            URL url = new URL(ip);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            while ((read = in.readLine()) != null) {
                inputLine += read;
            }
            String ObjJson = inputLine.substring(inputLine.indexOf("=") + 1, inputLine.length() - 1);
            JSONObject jsonObj = JSON.parseObject(ObjJson);
            toIp = jsonObj.getString("cip");
        } catch (Exception e) {
            toIp = "";
        }
        return toIp;*/
    }
}

2、获取高德地图的城市code

@Override
    public String getAdcode(String ipAddr) {

        String request = ipUrl + "key=" + key + "&ip=" + ipAddr + "&output=JSON";
        //String request = ipUrl + "key=" + key + "&output=JSON";
        String res = HttpUtil.get(request);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String status = jsonObject.getString("status");
        if (!"1".equals(status))
            throw new OtherException("获取ip方式错误!");

        String infocode = jsonObject.getString("infocode");
        if (!"10000".equals(infocode))
            throw new OtherException("获取ip返回转态失败!");

        return jsonObject.getString("adcode");
    }

3、根据code获取天气

@Override
    public WeatherDTO getWeather(String city) {

        String request = url + city + "&key=" +  key;
        String res = HttpUtil.get(request);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String lives = jsonObject.getString("lives");
        Object o = JSONObject.parseArray(lives).get(0);
        JSONObject weather = JSONObject.parseObject(o.toString());

        WeatherDTO weatherDTO = new WeatherDTO();
        weatherDTO.setProvince(weather.getString("province"));
        weatherDTO.setCity(weather.getString("city"));
        weatherDTO.setWindpower(weather.getString("windpower"));
        weatherDTO.setWeather(weather.getString("weather"));
        weatherDTO.setTemperature(weather.getString("temperature"));
        weatherDTO.setHumidity(weather.getString("humidity"));
        weatherDTO.setWinddirection(weather.getString("winddirection"));

        return weatherDTO;

4、DTO

@Data
public class WeatherDTO implements Serializable {

    @ApiModelProperty(value = "省份")
    private String province;

    @ApiModelProperty(value = "城市")
    private String city;

    @ApiModelProperty(value = "天气现象")
    private String weather;

    @ApiModelProperty(value = "实时气温,单位:摄氏度")
    private String temperature;

    @ApiModelProperty(value = "风向描述")
    private String winddirection;

    @ApiModelProperty(value = "风力级别,单位:级")
    private String windpower;

    @ApiModelProperty(value = "空气湿度")
    private String humidity;

    @ApiModelProperty(value = "数据发布的时间")
    private String reporttime;

}

5、获取天气

@GetMapping("/weather")
    @ApiOperation(value = "获取天气", notes = "根据city获取天气预报", response = WeatherDTO.class)
    public CommonResult getWeather(HttpServletRequest request) throws SocketException {

        String ipAddr = IpInfoUtil.getIpAddr(request);
        log.info("获取用户ip地址====================>,{}", ipAddr);

        //ipAddr = "120.36.246.78";
        String adcode = farmAreaService.getAdcode(ipAddr);
        WeatherDTO weather = farmAreaService.getWeather(adcode);

        return CommonResult.success(weather);
    }

 

标签:String,getString,api,ip,request,weatherDTO,weather,高德
From: https://www.cnblogs.com/ki16/p/16838133.html

相关文章

  • [Typescript] 75. Easy - Push
    Implementthegenericversionof Array.pushForexample:typeResult=Push<[1,2],'3'>//[1,2,'3'] /*_____________YourCodeHere_____________*/t......
  • [Typescript] 77. Easy - Unshift
    Implementthetypeversionof Array.unshiftForexample:typeResult=Unshift<[1,2],0>//[0,1,2,] /*_____________YourCodeHere_____________*/t......
  • [Typescript] 76. Easy - Parameters
    Implementthebuilt-inParametersgenericwithoutusingit.Forexample:constfoo=(arg1:string,arg2:number):void=>{}typeFunctionParamsType=MyPara......
  • 代码随想录day28 | 93. 复原 IP 地址 78.子集 90. 子集 II
    93.复原IP地址题目|文章思路1.先判断每个部分是不是符合要求2.如果符合要求则加入path,递归下一层3.当遍历到字符串末尾,如果有四层,则加入结果,否则直接返回。实现......
  • CSharp: The single-responsibility principle (SRP) in donet core 6
    SingleResponsibilityPrincipleSOLIDDesignPatternsSOLIDisanacronymforfiveprinciplesofarchitecture.S–SingleResponsibilityPrincipleO–OpenClo......
  • 2.14 解压压缩包 zipobj.extract() zipobj.extractall()
    解压压缩包  zipobj.extract()    #解压压缩包的某个文件importzipfilewithzipfile.ZipFile('我的文件夹.zip','r')aszipobj:zipobj.extract('......
  • 【笔记05】Javascript - 基本概念 - (函数递归)
    先看一个试题: 求n的阶乘通常,我们会写:functionfac(num){varres=1;for(vari=1;i<=num;i++){res*=i;}returnres;}观察阶乘可以发现两个特点:特点一:......
  • IP 地址切换脚本
    @echooffcolor00modeconcols=80lines=30titleIP模式切换脚本:startclsecho=echo============================================================================ec......
  • ShiPinThreadHandleRequest
    importcom.alibaba.fastjson.JSONException;importcom.alibaba.fastjson.JSONObject;importjavax.ws.rs.core.HttpHeaders;importjavax.ws.rs.core.MediaType;imp......
  • JavaScript--DOM
    一、DOM的概述1、文档对象模型(DOM,DocumentObjectModel)是HTML和XML文档的编程接口。DOM表示由多层节点构成的文档,通过它开发者可以添加、删除和修改页面的各个部分......