本实例实现在jsp页面实现查询全国城市天气预报的功能,供大家参考,具体内容如下
实例目录:
包com.util; 进口java.io.BufferedReader; 进口java.io.FileOutputStream; 进口java.io.IOException; 进口java.io.InputStream; 进口java.io.InputStreamReader; 进口java.net.HttpURLConnection; 进口java.net.MalformedURLException; 进口java.net.URL; 进口java.nio.ByteBuffer; 进口java.nio.channels.FileChannel; 公共类NetUtilImpl实现NetUtil { @Override 公共字符串getJson(字符串url)抛出IOException { HttpURLConnection连接=零; URL url2=新网址(URL); 连接=(HttpURLConnection) url2.openConnection ();/*对和风天气提供的链接进行连接*/connection.connect ();/*获取状态码*/int重新编码=connection.getResponseCode (); BufferedReader BufferedReader=零; json字符串=新的字符串();/*如果连接成功*/如果(重新编码==200){/*对数据进行读,并且封装到json这个字符串,并且返回json */InputStream InputStream=connection.getInputStream (); bufferedReader=new bufferedReader(新InputStreamReader (inputStream, " utf - 8 ")); 字符串的字符串=零; 在((string=bufferedReader.readLine ()) !=null) { json=json字符串+;=ByteBuffer ByteBuffer缓冲区。包装(新字符串(字符串).getBytes (" utf - 8 ")); } } 返回json; } } >之前
对json字符串进行解析,这里使用谷歌的gson工具包:
包com.util; 进口java.io.FileReader; 进口java.util.ArrayList; 进口并不知道; 进口com.google.gson.JsonArray; 进口com.google.gson.JsonObject; 进口com.google.gson.JsonParser; 公共类JsonUtilImpl实现JsonUtil { @Override 公共ListgetData (String json) { ArrayList 列表=new ArrayList (); JsonParser JsonParser=new JsonParser ();//json解析器 JsonObject对象=(JsonObject) jsonParser.parse (json);//创建JsonObject对象 获取数组=object.get(“结果”).getAsJsonArray();//得到json数组 JsonObject sJsonObject=array.get (0) .getAsJsonObject();//按索引得到其中具体数据 JsonObject位置=sJsonObject.get(“位置”).getAsJsonObject (); JsonObject现在=sJsonObject.get(“现在”).getAsJsonObject (); lists.add (location.get(“名字”).getAsString ()); lists.add (now.get(“文本”).getAsString ()); lists.add (now.get(温度).getAsString ());//lists.add (now.get(“湿度”).getAsString ());//lists.add (now.get (wind_speed) .getAsString ()); 返回列表; } } >之前 <强>完整代码:强>
控制器层:
包com.web; 进口java.io.IOException; 进口并不知道; 进口javax.annotation.Resource; 进口org.springframework.stereotype.Controller; 进口org.springframework.ui.Model; 进口org.springframework.web.bind.annotation.RequestMapping; 进口org.w3c.dom.ls.LSException; 进口com.google.common.collect.Lists; 进口com.sun.org.apache.bcel.internal.generic.NEW; 进口com.util.JsonUtil; 进口com.util.JsonUtilImpl; 进口com.util.NetUtil; 进口com.util.NetUtilImpl; @ controller @RequestMapping("/我们”) 公共类森林{ NetUtilImpl NetUtilImpl=new NetUtilImpl (); JsonUtilImpl JsonUtilImpl=new JsonUtilImpl (); 森林@RequestMapping (“/? 城市森林公共字符串(字符串、模型模型)抛出IOException { 字符串url=" https://api.seniverse.com/v3/weather/now.json& # 63;关键=mtpmwyecaphmrzwc&位置=" +城市+”,语言=zh-Hans&单位=c”; 字符串数据=https://www.yisu.com/zixun/netUtilImpl.getJson (url); 列表SpringMVC结合天气api实现天气查询