阿里云--全国天气预报查询(免费版)--全国城市的列表
来源:互联网 发布:淘宝硅胶充气娃娃 编辑:程序博客网 时间:2024/04/28 21:10
http://download.csdn.net/download/my_blankness/10108322
结果是:把查询出来的全国城市的列表都制成一个表格存放
创建一个maven项目
数据库创建表
create table t_city(cityid int primary key,parentid int not null,citycode VARCHAR(255),city varchar(255));
数据库连接的代码
DBUtil.java
package com.zhiyou.util;import java.io.InputStream;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Properties;import javax.sql.DataSource;import org.apache.log4j.Logger;import com.alibaba.druid.pool.DruidDataSourceFactory;/** * 数据库相关操作 * * @author jack 1.获取数据库连接 2.释放资源 * */public class DBUtil { private static Logger log = Logger.getLogger(DBUtil.class); private static DataSource ds; static { try { InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties props = new Properties(); props.load(in); ds = DruidDataSourceFactory.createDataSource(props); log.info("数据库连接池初始化成功....."); } catch (Exception ex) { log.error("初始化数据库连接池异常:" + ex.getMessage()); } } /** * 获取数据连接 * * @return */ public static Connection getConnection() { try { Connection conn = ds.getConnection(); log.info("获取数据库连接成功!"); return conn; } catch (SQLException e) { log.error("获取数据库连接失败" + e.getMessage()); } return null; } /** * 释放资源 * * @param conn * @param pst */ public static void close(Connection conn, PreparedStatement pst) { try { pst.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } /** * 释放资源 * * @param conn * @param pst * @param rs */ public static void close(Connection conn, PreparedStatement pst, ResultSet rs) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { pst.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }}
jdbc.properties
package com.zhiyou.util;import java.io.InputStream;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Properties;import javax.sql.DataSource;import org.apache.log4j.Logger;import com.alibaba.druid.pool.DruidDataSourceFactory;/** * 数据库相关操作 * * @author jack 1.获取数据库连接 2.释放资源 * */public class DBUtil { private static Logger log = Logger.getLogger(DBUtil.class); private static DataSource ds; static { try { InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties props = new Properties(); props.load(in); ds = DruidDataSourceFactory.createDataSource(props); log.info("数据库连接池初始化成功....."); } catch (Exception ex) { log.error("初始化数据库连接池异常:" + ex.getMessage()); } } /** * 获取数据连接 * * @return */ public static Connection getConnection() { try { Connection conn = ds.getConnection(); log.info("获取数据库连接成功!"); return conn; } catch (SQLException e) { log.error("获取数据库连接失败" + e.getMessage()); } return null; } /** * 释放资源 * * @param conn * @param pst */ public static void close(Connection conn, PreparedStatement pst) { try { pst.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } /** * 释放资源 * * @param conn * @param pst * @param rs */ public static void close(Connection conn, PreparedStatement pst, ResultSet rs) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { pst.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }}
log4j.properties
#\u5168\u5c40\u914d\u7f6elog4j.rootLogger=debug,console, file#debug \u6d4b\u8bd5\u9636\u6bb5\u4f7f\u7528#info \u4e0a\u7ebf#\u63a7\u5236\u53f0\u65e5\u5fd7\u8f93\u51falog4j.appender.console=org.apache.log4j.ConsoleAppenderlog4j.appender.console.layout=org.apache.log4j.PatternLayoutlog4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%p] %l %m %n#\u8f93\u51fa\u5230\u6587\u4ef6log4j.appender.file=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.file.File=./logs/access.loglog4j.appender.file.DatePattern='_'yyyyMMdd'.log'log4j.appender.file.encoding=UTF-8log4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%p] %l %m%n#\u8ffd\u52a0\u6a21\u5f0f\u8bb0\u5f55\u65e5\u5fd7log4j.appender.file.Append=true
R.java
package com.zhiyou.model;import java.util.List;public class R { private String status; private String msg; private List<City> result; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<City> getResult() { return result; } public void setResult(List<City> result) { this.result = result; }}
City.java
package com.zhiyou.model;public class City { private int cityid; private int parentid; private String citycode; private String city;// 城市名称 public int getCityid() { return cityid; } public void setCityid(int cityid) { this.cityid = cityid; } public int getParentid() { return parentid; } public void setParentid(int parentid) { this.parentid = parentid; } public String getCitycode() { return citycode; } public void setCitycode(String citycode) { this.citycode = citycode; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return cityid + " " + parentid + " " + citycode + " " + city; }}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zhiyou</groupId> <artifactId>api</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.15</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.2.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.2.1</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-util</artifactId> <version>9.3.7.v20160115</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.5</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.20</version> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.29</version> </dependency> <!-- log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> </dependencies> <build> <finalName>api</finalName> <plugins> <plugin> <!-- 配置插件 --> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <configuration> <port>8081</port> <path>/api</path> <uriEncoding>UTF-8</uriEncoding> </configuration> </plugin> </plugins> </build></project>
App.java
package com.zhiyou;import java.sql.Connection;import java.sql.PreparedStatement;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.http.HttpResponse;import org.apache.http.util.EntityUtils;import com.alibaba.fastjson.JSON;import com.zhiyou.model.City;import com.zhiyou.model.R;import com.zhiyou.util.DBUtil;import com.zhiyou.util.HttpUtils;public class App { public static void main(String[] args) { String host = "http://jisutqybmf.market.alicloudapi.com"; //path中要写city String path = "/weather/city"; String method = "GET"; String appcode = "d4fd1eaf06b442eea3b364bce13dd979"; Map<String, String> headers = new HashMap<String, String>(); //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105 headers.put("Authorization", "APPCODE " + appcode); Map<String, String> querys = new HashMap<String, String>(); querys.put("city", "安顺"); querys.put("citycode", "citycode"); querys.put("cityid", "cityid"); querys.put("ip", "ip"); querys.put("location", "location"); try { /** * 重要提示如下: * HttpUtils请从 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java * 下载 * * 相应的依赖请参照 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml */ HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);// System.out.println(response.toString()); //获取response的body// System.out.println(EntityUtils.toString(response.getEntity())); String json=EntityUtils.toString(response.getEntity()); R r = JSON.parseObject(json, R.class); System.out.println(r.getStatus()); System.out.println(r.getMsg()); List<City> list = r.getResult(); Connection conn = DBUtil.getConnection(); String sql="insert into t_city values(?,?,?,?)"; PreparedStatement pst = conn.prepareStatement(sql); for(City c:list){ pst.setInt(1, c.getCityid()); pst.setInt(2, c.getParentid()); pst.setString(3, c.getCitycode()); pst.setString(4, c.getCity());// System.out.println(c); pst.execute(); } DBUtil.close(conn, pst);// System.out.println(); } catch (Exception e) { e.printStackTrace(); } }}
根据上面的重要提示,配置pom.xml和HttpUtils.java的工具类
HttpUtils.java
package com.zhiyou.util;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.List;import java.util.Map;import javax.net.ssl.SSLContext;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;import org.apache.commons.lang.StringUtils;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpDelete;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpPut;import org.apache.http.conn.ClientConnectionManager;import org.apache.http.conn.scheme.Scheme;import org.apache.http.conn.scheme.SchemeRegistry;import org.apache.http.conn.ssl.SSLSocketFactory;import org.apache.http.entity.ByteArrayEntity;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;public class HttpUtils { /** * get * * @param host * @param path * @param method * @param headers * @param querys * @return * @throws Exception */ public static HttpResponse doGet(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception { HttpClient httpClient = wrapClient(host); HttpGet request = new HttpGet(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } return httpClient.execute(request); } /** * post form * * @param host * @param path * @param method * @param headers * @param querys * @param bodys * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (bodys != null) { List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); for (String key : bodys.keySet()) { nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key))); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8"); formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8"); request.setEntity(formEntity); } return httpClient.execute(request); } /** * Post String * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (StringUtils.isNotBlank(body)) { request.setEntity(new StringEntity(body, "utf-8")); } return httpClient.execute(request); } /** * Post stream * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); } /** * Put String * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (StringUtils.isNotBlank(body)) { request.setEntity(new StringEntity(body, "utf-8")); } return httpClient.execute(request); } /** * Put stream * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); } /** * Delete * * @param host * @param path * @param method * @param headers * @param querys * @return * @throws Exception */ public static HttpResponse doDelete(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception { HttpClient httpClient = wrapClient(host); HttpDelete request = new HttpDelete(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } return httpClient.execute(request); } private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException { StringBuilder sbUrl = new StringBuilder(); sbUrl.append(host); if (!StringUtils.isBlank(path)) { sbUrl.append(path); } if (null != querys) { StringBuilder sbQuery = new StringBuilder(); for (Map.Entry<String, String> query : querys.entrySet()) { if (0 < sbQuery.length()) { sbQuery.append("&"); } if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) { sbQuery.append(query.getValue()); } if (!StringUtils.isBlank(query.getKey())) { sbQuery.append(query.getKey()); if (!StringUtils.isBlank(query.getValue())) { sbQuery.append("="); sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8")); } } } if (0 < sbQuery.length()) { sbUrl.append("?").append(sbQuery); } } return sbUrl.toString(); } private static HttpClient wrapClient(String host) { HttpClient httpClient = new DefaultHttpClient(); if (host.startsWith("https://")) { sslClient(httpClient); } return httpClient; } private static void sslClient(HttpClient httpClient) { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] xcs, String str) { } public void checkServerTrusted(X509Certificate[] xcs, String str) { } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = httpClient.getConnectionManager(); SchemeRegistry registry = ccm.getSchemeRegistry(); registry.register(new Scheme("https", 443, ssf)); } catch (KeyManagementException ex) { throw new RuntimeException(ex); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } }}
阅读全文
0 0
- 阿里云--全国天气预报查询(免费版)--全国城市的列表
- 阿里云API:全国天气预报查询(免费版)(C#实现)
- 全国天气预报城市代码
- 全国主要城市的DNS服务器列表
- js实现全国城市列表
- 全国市一级城市列表
- MVC实现全国城市列表
- 全国省份城市列表json
- 全国城市省份对应的二级下拉列表框
- 全国各主要城市的DNS地址查询
- 全国城市中心点(全)
- 利用google map 查询全国城市坐标
- 聚合数据全国天气预报--ajax 通过城市名取数据
- 全国 各地区县城 天气预报
- 全国天气预报api接口
- 全国仅四家!阿里云ET城市大脑入选国家AI开放创新平台
- 全国主机城市的DNS服务器
- 全国所有的省份及城市选择
- 弹出菜单第一次尝试(Dialog)
- Struts2在SSH框架中的配置
- C++输入输出
- 设计模式(3)-原型(Prototype)模式
- 命令行备忘
- 阿里云--全国天气预报查询(免费版)--全国城市的列表
- QBC查询
- 字体信息设置界面
- 小奇挖矿 解题报告
- 洛谷 3093 [USACO13DEC]牛奶调度Milk Scheduling
- 有关VMware(虚拟机)的配置问题
- spring只读事务属性和超时事务属性
- 按钮布局演示
- 关于c++异常的初接触try{}catch{}