通过ip获取位置和天气
一、RestTemplate配置
@Configuration public class RestConfig { // @Bean // @ConditionalOnMissingBean({RestOperations.class, RestTemplate.class}) // public RestTemplate restTemplate(ClientHttpRequestFactory factory) { // return new RestTemplate(factory); // } // // @Bean // @ConditionalOnMissingBean({ClientHttpRequestFactory.class}) // public ClientHttpRequestFactory simpleClientHttpRequestFactory() { // SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); // factory.setReadTimeout(30000); // factory.setConnectTimeout(30000); // return factory; // } @Bean(value = "restTemplate") public RestTemplate getRestTemplateBuilder(){ RestTemplate restTemplate = new RestTemplateBuilder() .setConnectTimeout(Duration.ofMillis(30000)) .setReadTimeout(Duration.ofMillis(30000)) .build(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8); stringHttpMessageConverter.setWriteAcceptCharset(true); List<MediaType> mediaTypeList = new ArrayList<>(); mediaTypeList.add(MediaType.ALL); for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) { if (restTemplate.getMessageConverters().get(i) instanceof StringHttpMessageConverter) { restTemplate.getMessageConverters().remove(i); restTemplate.getMessageConverters().add(i, stringHttpMessageConverter); } if(restTemplate.getMessageConverters().get(i) instanceof MappingJackson2HttpMessageConverter){ try{ ((MappingJackson2HttpMessageConverter) restTemplate.getMessageConverters().get(i)).setSupportedMediaTypes(mediaTypeList); }catch(Exception e){ e.printStackTrace(); } } } return restTemplate; } }
二、jsoup配置
<dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.12.1</version> </dependency>
二、service编写
@Service @Slf4j public class WeatherService { @Autowired private RestTemplate restTemplate; @Autowired private ObjectMapper objectMapper; public String getCurrentIp(HttpServletRequest request) { String ipAddress = null; try { ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if (ipAddress.equals("127.0.0.1")) { // 根据网卡取本机配置的IP InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress = inet.getHostAddress(); } } // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15 if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); } } } catch (Exception e) { ipAddress=""; } // ipAddress = this.getRequest().getRemoteAddr(); return ipAddress; } public String getPositionByCurrentIp(HttpServletRequest request) throws IOException { String ip = getCurrentIp(request); log.info(ip); return getPositionByIpFromIp138(ip); } public String getPositionByIpFromTaobao(String ip) throws JsonProcessingException { Map<String,String> map = new HashMap<>(); map.put("ip",ip); String result = restTemplate.getForObject("http://ip.taobao.com/service/getIpInfo.php?ip={ip}",String.class,map); JsonNode jsonNode = objectMapper.readTree(result); System.out.println(jsonNode.toString()); String response = jsonNode.get("data").get("city").asText(); return response; } public String getPositionByIpFromIp138(String ip) throws IOException { Document document = Jsoup.connect("http://www.ip138.com/iplookup.asp?action=2&ip="+ip).get(); //本站数据:上海市闵行区 电信 String addr = document.getElementsByClass("ul1").get(0).getElementsByTag("li").get(0).text(); String position = null; try{ position = addr.replaceAll("本站数据:","").replaceAll("特别行政区",""); log.info(position); String[] positions = position.substring(0,position.indexOf(" ")).split("省|市|县|区"); for (int i = positions.length-1; i >= 0; i--) { if (!StringUtils.isEmpty(positions[i])){ position = positions[i]; break; } } }catch (Exception e){} return position; } public String getWeatherByArea(String area){ String result = restTemplate.getForObject("http://wthrcdn.etouch.cn/weather_mini?city="+area,String.class); return result; } public String getWeatherByIp(String ip) throws IOException { String area = getPositionByIpFromIp138(ip); String result = restTemplate.getForObject("http://wthrcdn.etouch.cn/weather_mini?city="+area,String.class); return result; } public String getWeatherByCurrentIp(HttpServletRequest request) throws IOException { String area = getPositionByCurrentIp(request); String result = restTemplate.getForObject("http://wthrcdn.etouch.cn/weather_mini?city="+area,String.class); return result; } }
三、controller编写
@RestController public class WeatherController { @Autowired private WeatherService weatherService; @GetMapping("/weather") public String getWeather(HttpServletRequest request,@RequestParam(required = false) String area,@RequestParam(required = false) String ip) throws IOException { if (!StringUtils.isEmpty(ip)){ return weatherService.getWeatherByIp(ip); } if (!StringUtils.isEmpty(area)){ return weatherService.getWeatherByArea(area); } return weatherService.getWeatherByCurrentIp(request); } @GetMapping("/position") public String getCurrentLocation(HttpServletRequest request,@RequestParam(required = false) String ip) throws IOException { if (!StringUtils.isEmpty(ip)){ return weatherService.getPositionByIpFromIp138(ip); } return weatherService.getPositionByCurrentIp(request); } }
不积跬步无以至千里