首先你必须有一个百度的,访问应用(AK) ,否则就别往下读了
申请地址:http://lbsyun.baidu.com/apiconsole/key
注意:
写在前面-- java的类文件必须是utf-8,否则读出来的是乱码
1.功能是访问百度的天气api,配置相应的参数,得到对应的数据
http://api.map.baidu.com/telematics/v3/weather?location=116.3,39.9&ak=mhn3ZNqG82zvcFInkXL39oaz
地址location可以是经纬度,也可以是城市名称如北京
ak码是必须的,否则不能访问
还有一个参数是&output=json,不写的话解析的是xml
2.程序的主线是main中的两个:
new WeatherUtilsBaidu().getWeatherBaiduXML();//xml提取
和
new WeatherUtilsBaidu().getWeatherBaiduJSON();//json提取
3.数据的读取,一个是联网的,一个是自己copy下来自己读取这样是为了快速测试
4.xml的解析是常规的方式
json的读取用了两种方式,一个是Gson,一个是jsonObject;
本人推荐gson,因为遇到嵌套的多级关系时,只需建立对应的类即可,很方便
5.其他涉及:i/o读取,反射机制,嵌套循环模式
package com.tsingsoft.weather.util; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Field; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.google.gson.Gson; import net.sf.json.*; public class WeatherUtilsBaidu { public static void main(String[] args) throws Exception { /** * 百度 */ //xml提取 new WeatherUtilsBaidu().getWeatherBaiduXML(); //json提取 new WeatherUtilsBaidu().getWeatherBaiduJSON(); /** * json的提取练习 */ // testjson(); } /** * 百度接口 * @throws Exception */ // 参数类型 参数名称 是否必须 具体描述 // String ak true 开发者密钥 // String sn false 若用户所用ak的校验方式为sn校验时该参数必须。 // String location true 输入城市名或经纬度,城市名称如:北京,经纬度格式为lng,lat坐标如: location=116.305145,39.982368;城市天气预报中间"|"分隔,location=116.305145,39.982368| 122.305145,36.982368|…. // String output false 输出的数据格式,默认为xml格式,当output设置为’json’时,输出的为json格式的数据; // String coord_type false 请求参数坐标类型,默认为gcj02经纬度坐标。允许的值为bd09ll、bd09mc、gcj02、wgs84。bd09ll表示百度经纬度坐标,bd09mc表示百度墨卡托坐标,gcj02表示经过国测局加密的坐标。wgs84表示gps获取的坐标。 // 例子:http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=yourkey public void getWeatherBaiduXML() throws Exception { //http://api.map.baidu.com/telematics/v3/weather?location=116.3,39.9&ak=mhn3ZNqG82zvcFInkXL39oaz //location=北京 //output=json //第一级:<CityWeatherResponse> 第二级:<results> //第三级:<currentCity>北京市</currentCity> ; <weather_data>其中有 <date> <wind> <weather> <temperature> /** * xml */ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc =null; /** * url访问 */ // String url_s = "http://api.map.baidu.com/telematics/v3/weather?location=116.3,39.9&ak=mhn3ZNqG82zvcFInkXL39oaz"; // URL url = new URL(url_s); // URLConnection connection = url.openConnection(); // doc = builder.parse(connection.getInputStream()); /** * 提取本地访问 */ InputStream filein = new FileInputStream("E:/算法:天气预报/百度weather/baidu.xml"); doc = builder.parse(filein); System.out.println("百度天气:"); System.out.print("城市:"); NodeList nodeList = doc.getElementsByTagName("currentCity"); for(int i=0;i<nodeList.getLength();i++) { Node node = nodeList.item(i);//1个 result System.out.println(node.getTextContent()); } System.out.print("日期:"); nodeList = doc.getElementsByTagName("date"); for(int i=0;i<nodeList.getLength();i++) { Node node = nodeList.item(i);//1个 result System.out.println(node.getTextContent()); } System.out.println("风:"); nodeList = doc.getElementsByTagName("wind"); for(int i=0;i<nodeList.getLength();i++) { Node node = nodeList.item(i);//1个 result System.out.println(node.getTextContent()); } } public static void testjson(){ String json = "[{\"Id\":\"100\",\"number\":\"456\"},{\"Id\":\"100\",\"number\":\"123\"}]"; // String json="[{"Id":"100","number":"456"},{"Id":"100","number":"123"}]"; // 这里由于格式原因不能使用,这个只是一个对象,例子是数组的格式 // JSONObject o = (JSONObject)JSONSerializer.toJSON(json); JSONArray jsonNodes = JSONArray.fromObject(json); for (Object obj : jsonNodes) { JSONObject jsonNode = JSONObject.fromObject(obj); System.out.println(jsonNode.getLong("Id") + ":"+ jsonNode.getString("number")); } } public void getWeatherBaiduJSON() throws Exception { String json=""; StringBuffer sb= new StringBuffer(); Reader in=null; /** * url访问 */ URL url = new URL(getSend("116.3,39.9")); // URL url = new URL(getSend("北京")); URLConnection connection = url.openConnection(); in=new InputStreamReader(connection.getInputStream()); /** * 提取本地访问 */ // in = new FileReader("E:/算法:天气预报/百度weather/baidu.json"); //最好使用缓存读写 BufferedReader Bufin = new BufferedReader(in); /** * 方式一:易记忆,但只针对 BufferedReader */ String line = Bufin.readLine(); while (line != null) { sb.append(line); line = Bufin.readLine(); } /** * 方式二:不好记,通用性强 */ // char[] temp=new char[1024]; // int len=0; // while((len=Bufin.read(temp))!=-1){ // sb.append(temp,len); // } Bufin.close(); /** * 对于gson类方式:对象json不能[]开头,必须{}开头 */ // json= "["+sb.toString()+"]" ; json= sb.toString(); System.out.println(json); /** * 方式一:Gson,推荐 fromJsonToJava 类 * 定义类,直接生成对象 */ Gson gson = new Gson(); Status status = gson.fromJson(json,Status.class); System.out.println(status.getResults().get(0).getCurrentCity()+":"+status.getDate()); for(Weather wea:status.getResults().get(0).getWeather_data()){ System.out.println(wea.getDate()+"|"+wea.getWind()+"|"+wea.getTemperature()+"|"+wea.getWeather()); } /** * 方式二:JSONObject * 递归循环 */ // System.out.println("--递归提取json信息-----------------------------------------"); // getJsonValue(json); /** * 方式三:JSONObject * 循环封装,目前只有一层的,不能多个对象列表存储 */ // System.out.println("--获取一级对象-----------------------------------------"); // JSONObject jsonObject = JSONObject.fromObject(json); // Status statusJO = (Status) fromJsonToJava(jsonObject,Status.class); // System.out.println(statusJO.getStatus()); } private static Object fromJsonToJava(JSONObject json,Class pojo) throws Exception{ // 首先得到pojo所定义的字段 Field [] fields = pojo.getDeclaredFields(); // 根据传入的Class动态生成pojo对象 Object obj = pojo.newInstance(); for(Field field: fields){ // 设置字段可访问(必须,否则报错) field.setAccessible(true); // 得到字段的属性名 String name = field.getName(); // 这一段的作用是如果字段在JSONObject中不存在会抛出异常,如果出异常,则跳过。 try{ json.get(name); }catch(Exception ex){ continue; } System.out.println(name+":"+json.get(name)); if(json.get(name) != null && !"".equals(json.getString(name))){ // 根据字段的类型将值转化为相应的类型,并设置到生成的对象中。 if(field.getType().equals(Long.class) || field.getType().equals(long.class)){ field.set(obj,Long.parseLong(json.getString(name))); }else if(field.getType().equals(String.class)){ field.set(obj,json.getString(name)); } else if(field.getType().equals(Double.class) || field.getType().equals(double.class)){ field.set(obj,Double.parseDouble(json.getString(name))); } else if(field.getType().equals(Integer.class) || field.getType().equals(int.class)){ field.set(obj,Integer.parseInt(json.getString(name))); } else if(field.getType().equals(java.util.Date.class)){ field.set(obj,Date.parse(json.getString(name))); }else{ continue; } } } return obj; } /* * 递归遍历json所有子条目 */ public static String getJsonValue(String json) { if(!json.contains("{") && !json.contains("[") && json.contains(":")) { return json; } else if(json.equals("")){ return json; } else if(json.trim().charAt(0) == '{'){ String value = null; JSONObject jsonObject = JSONObject.fromObject(json); Iterator keyIter = jsonObject.keys(); while( keyIter.hasNext()) { String key = (String)keyIter.next(); value = jsonObject.get(key).toString(); getJsonValue(value); if(!value.contains("{") && !value.contains("[")) { System.out.println(key + " = " + value); } } return value; } else if(json.trim().charAt(0) == '[') { String value = null; JSONArray jsonArr = JSONArray.fromObject(json); for (int i = 0; i < jsonArr.size(); i++) { value = jsonArr.getJSONObject(i).toString(); getJsonValue(value); if(!value.contains("{") && !value.contains("[")) { System.out.println("----"+value); } } return value; } else { return "error"; } } private static String api = "http://api.map.baidu.com/telematics/v3/weather?"; private static String output = "json"; private static String ak = "mhn3ZNqG82zvcFInkXL39oaz"; public static String getSend(String str){ //将传进来的城市转码 try { str = URLEncoder.encode(str,"utf-8"); } catch (Exception e) { e.printStackTrace(); } //拼接url StringBuffer buf = new StringBuffer(); buf.append("location="); buf.append(str); buf.append("&output="); buf.append(output); buf.append("&ak="); buf.append(ak); String param = buf.toString(); //这是接收百度API String urlName = api + param; return urlName; } } class Status{ private String error; private String status; private String date; private List<Results> results; public String getError() { return error; } public void setError(String error) { this.error = error; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public List<Results> getResults() { return results; } public void setResults(List<Results> results) { this.results = results; } } class Results{ private String currentCity; private List<Weather> weather_data; public String getCurrentCity() { return currentCity; } public void setCurrentCity(String currentCity) { this.currentCity = currentCity; } public List<Weather> getWeather_data() { return weather_data; } public void setWeather_data(List<Weather> weatherData) { weather_data = weatherData; } } class Weather{ private String date; private String dayPictureUrl; private String nightPictureUrl; private String weather; private String wind; private String temperature; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getDayPictureUrl() { return dayPictureUrl; } public void setDayPictureUrl(String dayPictureUrl) { this.dayPictureUrl = dayPictureUrl; } public String getNightPictureUrl() { return nightPictureUrl; } public void setNightPictureUrl(String nightPictureUrl) { this.nightPictureUrl = nightPictureUrl; } public String getWeather() { return weather; } public void setWeather(String weather) { this.weather = weather; } public String getWind() { return wind; } public void setWind(String wind) { this.wind = wind; } public String getTemperature() { return temperature; } public void setTemperature(String temperature) { this.temperature = temperature; } }原文链接:https://www.f2er.com/xml/297132.html