package com.ruoyi.web.controller.gzh; import org.json.JSONException;import…
- User
package com.ruoyi.web.controller.gzh;
import org.json.JSONException;import org.json.JSONObject; import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.nio.charset.StandardCharsets;import java.util.HashMap;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern; public class GetLocationAndIP {
private static String readAll(BufferedReader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); }
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { try (InputStream is = new URL(url).openStream()) { BufferedReader rd = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); String jsonText = readAll(rd); return new JSONObject(jsonText); } } public Map<String, Object> getAddress() { String ip = ""; // 这个网址似乎不能了用了 // String chinaz = "http://ip.chinaz.com"; // 改用了太平洋的一个网址 String chinaz = "http://whois.pconline.com.cn/"; StringBuilder inputLine = new StringBuilder(); String read = ""; URL url = null; HttpURLConnection urlConnection = null; BufferedReader in = null; Map<String, Object> map = new HashMap<>(); try { url = new URL(chinaz); urlConnection = (HttpURLConnection) url.openConnection(); // 如有乱码的,请修改相应的编码集,这里是 gbk in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "gbk")); while ((read = in.readLine()) != null) { inputLine.append(read).append("\r\n"); } } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } // 这个是之前的正则表达式, // Pattern p = Pattern.compile("\<dd class\="fz24">(.?)\<\/dd>"); // 通过正则表达式匹配我们想要的内容,根据拉取的网页内容不同,正则表达式作相应的改变 Pattern p = Pattern.compile("显示IP地址为(.?)的位置信息"); Matcher m = p.matcher(inputLine.toString()); if (m.find()) { String ipstr = m.group(0); // 这里根据具体情况,来截取想要的内容 ip = ipstr.substring(ipstr.indexOf("为") + 2, ipstr.indexOf("的") - 1); map.put("ip", ip); } JSONObject json = null; try { // 这里调用百度的ip定位api服务 详见 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=laOQElaF53xGGBjscGtrd10nN4j1zGki&ip=" + ip); //city = (((JSONObject) ((JSONObject) json.get("content")).get("address_detail")).get("city")).toString(); map.put("city", ((JSONObject) ((JSONObject) json.get("content")).get("address_detail")).get("city").toString()); } catch (Exception e) { e.printStackTrace(); } return map; } public static String getLocalCityName() { GetLocationAndIP getLocationANDIp = new GetLocationAndIP(); Map<String, Object> map = getLocationANDIp.getAddress(); String city = map.get("city").toString(); return city.substring(0, city.length() - 1); } public static void main(String[] args) { GetLocationAndIP getLocationANDIp = new GetLocationAndIP(); Map<String, Object> map = getLocationANDIp.getAddress(); String city = map.get("city").toString(); String city_1 = city.substring(0, city.length() - 1); System.out.println(city_1); }} 将这个类格式化一下
- Assistant
Certainly! Here's the formatted version of the
GetLocationAndIPclass:package com.ruoyi.web.controller.gzh; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GetLocationAndIP { private static String readAll(BufferedReader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException { try (InputStream is = new URL(url).openStream()) { BufferedReader rd = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); String jsonText = readAll(rd); return new JSONObject(jsonText); } } public Map<String, Object> getAddress() { String ip = ""; // 这个网址似乎不能用了,改用了太平洋的一个网址 String chinaz = "http://whois.pconline.com.cn/"; StringBuilder inputLine = new StringBuilder(); String read = ""; HttpURLConnection urlConnection = null; BufferedReader in = null; Map<String, Object> map = new HashMap<>(); try { URL url = new URL(chinaz); urlConnection = (HttpURLConnection) url.openConnection(); // Modify encoding set if there is garbled text, here it is gbk in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "gbk")); while ((read = in.readLine()) != null) { inputLine.append(read).append("\r\n"); } } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } // Modify regex pattern according to the new content Pattern p = Pattern.compile("显示IP地址为(.*?)的位置信息"); Matcher m = p.matcher(inputLine.toString()); if (m.find()) { String ipstr = m.group(0); // Extract required content ip = ipstr.substring(ipstr.indexOf("为") + 2, ipstr.indexOf("的") - 1); map.put("ip", ip); } try { // Baidu IP location API, refer to http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htm JSONObject json = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=laOQElaF53xGGBjscGtrd10nN4j1zGki&ip=" + ip); map.put("city", ((JSONObject) ((JSONObject) json.get("content")).get("address_detail")).get("city").toString()); } catch (Exception e) { e.printStackTrace(); } return map; } public static String getLocalCityName() { GetLocationAndIP getLocationANDIp = new GetLocationAndIP(); Map<String, Object> map = getLocationANDIp.getAddress(); String city = map.get("city").toString(); return city.substring(0, city.length() - 1); } public static void main(String[] args) { GetLocationAndIP getLocationANDIp = new GetLocationAndIP(); Map<String, Object> map = getLocationANDIp.getAddress(); String city = map.get("city").toString(); String city_1 = city.substring(0, city.length() - 1); System.out.println(city_1); } }This formatted version keeps the existing logic intact and organizes the code for better readability by properly aligning blocks, spaces, and comments.
- User
package com.ruoyi.web.controller.gzh; import com.ruoyi.common.core.domain.AjaxResult;import com.ruoyi.common.utils.http.HttpUtils;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController; import java.io.UnsupportedEncodingException;import java.net.URLEncoder; @RestControllerpublic class WeatherController { @GetMapping("/getWeatherByLocalIP") public AjaxResult getWeather() throws UnsupportedEncodingException { AjaxResult result = AjaxResult.success(); String localCityName = GetLocationAndIP.getLocalCityName(); //调用天气API String encodeCity = URLEncoder.encode(localCityName, "UTF-8"); System.out.println(encodeCity); String url = "http://apis.juhe.cn/simpleWeather/query?city=" + encodeCity + "&key=81fe33a6077267b2e4ae2967af47eeb7"; String weatherInfo = HttpUtils.sendGet(url); result.put("msg", weatherInfo); return result; } }将这个类格式化一下
- Assistant
Certainly! Here's the formatted version of the
WeatherControllerclass:package com.ruoyi.web.controller.gzh; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.utils.http.HttpUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; @RestController public class WeatherController { @GetMapping("/getWeatherByLocalIP") public AjaxResult getWeather() throws UnsupportedEncodingException { AjaxResult result = AjaxResult.success(); String localCityName = GetLocationAndIP.getLocalCityName(); // Encode city name for the API request String encodeCity = URLEncoder.encode(localCityName, "UTF-8"); System.out.println(encodeCity); // Replace with the URL of the weather API service String url = "http://apis.juhe.cn/simpleWeather/query?city=" + encodeCity + "&key=81fe33a6077267b2e4ae2967af47eeb7"; // Send GET request to fetch weather information String weatherInfo = HttpUtils.sendGet(url); result.put("msg", weatherInfo); return result; } }The code is now formatted for improved readability, with consistent indentation and spacing between declarations. Comments have been added or enhanced to provide clarity on code intentions.
- User
<el-button type="success" @click="handleWeather">当前城市天气 {{ city }} {{ weather.realtime.temperature }}℃ {{ weather.realtime.direct }} {{ weather.realtime.power }} {{ weather.realtime.humidity }}% {{ weather.realtime.info }} {{ item.direct }} {{ item.temperature }} {{ item.weather }}
格式化
- Assistant
Here's the formatted version of your Vue component:
<template> <div> <el-row style="margin-top: 30px;" :gutter="20"> <el-col :offset="10" :span="4"> <el-button type="success" @click="handleWeather">当前城市天气</el-button> </el-col> </el-row> <el-row :gutter="20" v-if="city.length > 0"> <el-col :offset="2" :span="20"> <el-descriptions title="当前实时天气"> <el-descriptions-item label="当前城市">{{ city }}</el-descriptions-item> <el-descriptions-item label="温度">{{ weather.realtime.temperature }}℃</el-descriptions-item> <el-descriptions-item label="风向">{{ weather.realtime.direct }}</el-descriptions-item> <el-descriptions-item label="风力">{{ weather.realtime.power }}</el-descriptions-item> <el-descriptions-item label="湿度">{{ weather.realtime.humidity }}%</el-descriptions-item> <el-descriptions-item label="天气状况">{{ weather.realtime.info }}</el-descriptions-item> </el-descriptions> </el-col> </el-row> <el-row v-for="item in weather.future" :key="item.date" style="margin-top: 30px;" :gutter="20"> <el-col :offset="2" :span="20"> <el-descriptions :title="item.date" :column="4"> <el-descriptions-item label="风向">{{ item.direct }}</el-descriptions-item> <el-descriptions-item label="温度">{{ item.temperature }}</el-descriptions-item> <el-descriptions-item label="天气情况">{{ item.weather }}</el-descriptions-item> </el-descriptions> </el-col> </el-row> </div> </template> <script> import { getWeather } from "@/api/gzh/weather"; export default { name: "weather", data() { return { city: "", weather: { realtime: {}, future: [] } }; }, methods: { handleWeather() { getWeather() .then(res => { const weatherInfo = JSON.parse(res.msg); this.city = weatherInfo.result.city; this.weather.realtime = weatherInfo.result.realtime; this.weather.future = weatherInfo.result.future; console.log(weatherInfo); }) .catch(err => { console.error(err); }); } } }; </script> <style scoped> </style>This formatted version makes the code more readable by arranging the template, script, and styling sections neatly and ensuring proper indentation and spacing.
- User
import request from "@/utils/request"; // 查询参数列表export function getWeather() { return request({ url: '/getWeatherByLocalIP', method: 'get', })}格式化1
- Assistant
Here's the formatted version of your JavaScript module:
import request from "@/utils/request"; // 查询参数列表 export function getWeather() { return request({ url: '/getWeatherByLocalIP', method: 'get', }); }In this formatted version, the import statement and function definition are clearly separated, and the function's body is properly indented for better readability. Additionally, the comment is placed on a separate line to clearly indicate its context.