├── .classpath ├── .gitignore ├── .project ├── .settings ├── org.eclipse.core.resources.prefs └── org.eclipse.jdt.core.prefs ├── README.md ├── SQL部分.sql ├── pom.xml ├── src ├── main │ ├── java │ │ ├── entity │ │ │ ├── GdNavLinkNJ.java │ │ │ └── GdNavLink_hibernate.java │ │ ├── gaode │ │ │ ├── GetNav.java │ │ │ ├── GetNavNJ.java │ │ │ └── response_example.json │ │ └── utils │ │ │ ├── HibernateUtils.java │ │ │ ├── HttpClientResult.java │ │ │ ├── HttpClientUtils.java │ │ │ └── JPAUtil.java │ └── resources │ │ └── META-INF │ │ └── persistence.xml └── test │ └── java │ └── gaode │ └── TestClass.java └── target └── classes └── META-INF └── MANIFEST.MF /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | gaode2 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/test/java=UTF-8 4 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 3 | org.eclipse.jdt.core.compiler.compliance=1.8 4 | org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled 5 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 6 | org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore 7 | org.eclipse.jdt.core.compiler.release=disabled 8 | org.eclipse.jdt.core.compiler.source=1.8 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --------------------- 2020年12月更新------------------------- 2 | 功能一: 3 | 南京市东南大学至新街口区域,道路车速获取的代码. 4 | 核心代码: 5 | src/main/entity/GdNavLinkNJ.java 6 | src/main/gaode/GetNavNJ.java 7 | --------------------- end ------------------------- 8 | 9 | 10 | --------------------- 2020年1月更新------------------------- 11 | 功能二: 12 | 利用高德路径规划接口获取路网 13 | 核心代码: 14 | src/main/entity/GdNavLink_hibernate.java 15 | src/main/gaode/GetNav.java 16 | "SQL部分.sql" 17 | ------------------------ end ------------------------- 18 | 19 | 20 | 概述---------- 21 | 语言: JAVA 22 | 项目管理方式: maven 23 | 数据库: ORACLE 24 | 持久化框架: hibernate. 使用该持久化框架的目的是方便大家切换数据库为自己的偏好(如postSQL/MySQL等) 25 | 26 | 27 | 28 | 如何使用---------- 29 | 1. 构建maven工程 30 | 2. maven无法自动添加oracle数据库的jdbc驱动,需要手动安装该驱动(ojdbc6-11.2.0.1.0.jar),oracle版权原因, 我就不上传这个jar包了, 需要请自行百度,联系我也行. 31 | 3. 在main/resources/META-INF/persistence.xml中修改数据库连接参数 32 | 4. 在getHttpReq方法中填入你自己申请的KEY 33 | 5. SQL部分。仅功能二用到,功能一不用。在数据库中新建表GD_NAV_POINT和GD_NAV_TRAFFIC,详见“SQL部分.sql”,可以用你自己的方法构造OD点对,也可以参照公众号教程中的操作实例 34 | 6. 运行: 功能一: 运行src/main/java/gaode/GetNavNJ.java 中的main方法; 功能二: 运行src/main/java/gaode/GetNavTrafficHibernate.java中的main方法. 35 | 7. SQL部分(仅功能二需要运行)。回到“SQL部分.sql”, 进行连通性和拓扑性的批量处理。 36 | 8. 最后在数据库中导出表GD_NAV_TRAFFIC_2, 即为最终路网。 37 | 38 | 39 | 建议: 40 | 1. 建议先学习功能二, 再学习功能一. 不然你很难理解功能一每个步骤的意图(尽管有注释). 41 | 2. 看代码时一定要结合着公众号文章教程, 原因同上. 42 | 43 | 44 | 作者公众号: 数牍小点子 45 | 微信: xuxinkun0591 46 | -------------------------------------------------------------------------------- /SQL部分.sql: -------------------------------------------------------------------------------- 1 | /* 规律总结: 2 | 1.在信号灯左转处,没有左转弧线,道路会缺失;在非信号灯双向路左转处,有时候会断开,有时候不会 3 | 2.在部分掉头处,导航路径(道路)会缺失 4 | 3.连续间隔15分钟访问某tmc,获得step的速度,速度会一直变. 5 | 4.最靠近交叉口的tmc速度一天到晚都很低,应该是考虑了信号灯等待时间. 6 | 5.有一些小路高德路况为"未知",在官方地图上也未显示,这些小路的速度(路程/时间)会给出一个相对固定的值(比如9km/h) 7 | */ 8 | 9 | /* 第一步 */ 10 | --1.1 创建OD点对表, 用于设置导航起终点, 该表可直接在ArcMap中编辑 11 | -- DROP TABLE "XXK"."GD_NAV_POINT" ; 12 | CREATE TABLE "XXK"."GD_NAV_POINT" 13 | ( "OBJECTID" NUMBER(*,0) NOT NULL ENABLE, 14 | "PROJECT" NVARCHAR2(50), 15 | "SHAPE" "MDSYS"."SDO_GEOMETRY" , 16 | "SE_ANNO_CAD_DATA" BLOB 17 | ); 18 | --1.2 生成表GD_NAV_POINT的视图V_GD_NAV_POINT, 按高德接口要求构造起终点坐标, java将直接访问该视图 19 | CREATE OR REPLACE VIEW v_gd_nav_point as 20 | select TO_CHAR(ROUND(a.shape.sdo_point.x,6))||','||TO_CHAR(ROUND(a.shape.sdo_point.y,6)) S, --起点 21 | TO_CHAR(ROUND(b.shape.sdo_point.x,6))||','||TO_CHAR(ROUND(b.shape.sdo_point.y,6)) E, --终点 22 | from GD_NAV_POINT a,GD_NAV_POINT b 23 | where a.objectid <> b.objectid 24 | ; 25 | SELECT * FROM v_gd_nav_point; 26 | 27 | 28 | 29 | 30 | /* 第二步 */ 31 | --2 创建路段表, 用于保存API路段数据 32 | -- drop table GD_NAV_TRAFFIC; 33 | create table GD_NAV_TRAFFIC( 34 | seq number(8) , 35 | dept varchar2(32), -- step/tmc 36 | tmcid number(8), -- 第几个tmc 37 | action varchar2(32), 38 | distance number(8), 39 | duration number(8), 40 | speed number(4), 41 | orientation varchar2(64), 42 | road varchar2(128), 43 | status varchar2(32), 44 | insert_time date, 45 | polyline sdo_geometry 46 | ); 47 | -- 创建空间索引 48 | CALL SDOINDEX('GD_NAV_TRAFFIC','polyline',4326); 49 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | jtxx 6 | gaode 7 | v1 8 | gaode_name 9 | gaode_desc 10 | 11 | 12 | 13 | 14 | 15 | org.apache.maven.plugins 16 | maven-compiler-plugin 17 | 3.5.1 18 | 19 | 1.8 20 | 1.8 21 | UTF-8 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | junit 31 | junit 32 | 4.9 33 | 34 | 35 | 36 | 37 | org.apache.httpcomponents 38 | httpclient 39 | 4.5.5 40 | 41 | 42 | 43 | com.google.code.gson 44 | gson 45 | 2.8.0 46 | 47 | 48 | 49 | org.hibernate 50 | hibernate-core 51 | 5.0.7.Final 52 | 53 | 54 | org.hibernate 55 | hibernate-spatial 56 | 5.0.7.Final 57 | 58 | 59 | org.hibernate 60 | hibernate-entitymanager 61 | 5.0.7.Final 62 | 63 | 64 | 65 | 66 | com.oracle 67 | ojdbc6 68 | 11.2.0.1.0 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/main/java/entity/GdNavLinkNJ.java: -------------------------------------------------------------------------------- 1 | package entity; 2 | 3 | 4 | import javax.persistence.Column; 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.GenerationType; 8 | import javax.persistence.Id; 9 | import javax.persistence.Table; 10 | 11 | import com.vividsolutions.jts.geom.Geometry; 12 | 13 | @Entity 14 | @Table(name = "GD_NAV_TRAFFIC_NJ") 15 | public class GdNavLinkNJ { 16 | @Id 17 | @GeneratedValue(strategy = GenerationType.AUTO) 18 | private Long seq; 19 | private Long batch; 20 | private Long linkid; 21 | private String dept; 22 | private Long tmcid; 23 | private String action; 24 | private Long distance; 25 | private Long duration; 26 | private Long speed; 27 | private String orientation; 28 | private String road; 29 | private String status; 30 | //@Temporal(TemporalType.TIMESTAMP) //指定时间格式 31 | @Column(name="insert_time") //指定特定的列名 32 | private java.sql.Timestamp insertTime; 33 | private Geometry polyline; 34 | 35 | public GdNavLinkNJ() { 36 | super(); 37 | } 38 | 39 | public GdNavLinkNJ(Long batch,Long linkid,String dept, Long tmcid, String action, Long distance, 40 | Long duration, Long speed,String orientation, String road, String status, java.sql.Timestamp insertTime, Geometry polyline) { 41 | super(); 42 | this.batch=batch; 43 | this.linkid=linkid; 44 | this.dept = dept; 45 | this.tmcid = tmcid; 46 | this.action = action; 47 | this.distance = distance; 48 | this.duration = duration; 49 | this.speed = speed; 50 | this.orientation = orientation; 51 | this.road = road; 52 | this.status = status; 53 | this.insertTime = insertTime; 54 | this.polyline = polyline; 55 | } 56 | 57 | public Long getBatch() { 58 | return batch; 59 | } 60 | 61 | public void setBatch(Long batch) { 62 | this.batch = batch; 63 | } 64 | 65 | public Long getLinkid() { 66 | return linkid; 67 | } 68 | 69 | public void setLinkid(Long linkid) { 70 | this.linkid = linkid; 71 | } 72 | 73 | public Long getSeq() { 74 | return seq; 75 | } 76 | 77 | public void setSeq(Long seq) { 78 | this.seq = seq; 79 | } 80 | 81 | public String getDept() { 82 | return dept; 83 | } 84 | 85 | public void setDept(String dept) { 86 | this.dept = dept; 87 | } 88 | 89 | public Long getTmcid() { 90 | return tmcid; 91 | } 92 | 93 | public void setTmcid(Long tmcid) { 94 | this.tmcid = tmcid; 95 | } 96 | 97 | public String getAction() { 98 | return action; 99 | } 100 | 101 | public void setAction(String action) { 102 | this.action = action; 103 | } 104 | 105 | public Long getDistance() { 106 | return distance; 107 | } 108 | 109 | public void setDistance(Long distance) { 110 | this.distance = distance; 111 | } 112 | 113 | public Long getDuration() { 114 | return duration; 115 | } 116 | 117 | public void setDuration(Long duration) { 118 | this.duration = duration; 119 | } 120 | 121 | public Long getSpeed() { 122 | return speed; 123 | } 124 | 125 | public void setSpeed(Long speed) { 126 | this.speed = speed; 127 | } 128 | 129 | public String getOrientation() { 130 | return orientation; 131 | } 132 | 133 | public void setOrientation(String orientation) { 134 | this.orientation = orientation; 135 | } 136 | 137 | public String getRoad() { 138 | return road; 139 | } 140 | 141 | public void setRoad(String road) { 142 | this.road = road; 143 | } 144 | 145 | public String getStatus() { 146 | return status; 147 | } 148 | 149 | public void setStatus(String status) { 150 | this.status = status; 151 | } 152 | 153 | public java.sql.Timestamp getInsertTime() { 154 | return insertTime; 155 | } 156 | 157 | public void setInsertTime(java.sql.Timestamp insertTime) { 158 | this.insertTime = insertTime; 159 | } 160 | 161 | public Geometry getPolyline() { 162 | return polyline; 163 | } 164 | 165 | public void setPolyline(Geometry polyline) { 166 | this.polyline = polyline; 167 | } 168 | 169 | @Override 170 | public int hashCode() { 171 | return polyline.toText().toString().hashCode(); 172 | } 173 | @Override 174 | public boolean equals(Object o) { 175 | GdNavLinkNJ p2 = (GdNavLinkNJ)o; 176 | // 判定条件: 1.geom满足equals关系;2.方向相同 177 | boolean if_equal = polyline.toText().equals(p2.getPolyline().toText()) && 178 | orientation.equals(p2.getOrientation()); 179 | return if_equal; 180 | } 181 | 182 | } 183 | -------------------------------------------------------------------------------- /src/main/java/entity/GdNavLink_hibernate.java: -------------------------------------------------------------------------------- 1 | package entity; 2 | 3 | 4 | import javax.persistence.Column; 5 | import javax.persistence.Entity; 6 | import javax.persistence.GeneratedValue; 7 | import javax.persistence.GenerationType; 8 | import javax.persistence.Id; 9 | import javax.persistence.Table; 10 | 11 | import com.vividsolutions.jts.geom.Geometry; 12 | 13 | /* 14 | create table gd_nav_traffic( 15 | seq number(8) , 16 | dept varchar2(32), -- step/tmc 17 | tmcid number(8), -- 第几个tmc 18 | action varchar2(32), 19 | distance number(8), 20 | duration number(8), 21 | speed number(4), 22 | orientation varchar2(64), 23 | road varchar2(128), 24 | status varchar2(32), 25 | insert_time date, 26 | polyline sdo_geometry 27 | ); 28 | */ 29 | @Entity 30 | @Table(name = "GD_NAV_TRAFFIC") 31 | public class GdNavLink_hibernate { 32 | @Id 33 | @GeneratedValue(strategy = GenerationType.AUTO) 34 | private Long seq; 35 | private String dept; 36 | private Long tmcid; 37 | private String action; 38 | private Long distance; 39 | private Long duration; 40 | private Long speed; 41 | private String orientation; 42 | private String road; 43 | private String status; 44 | //@Temporal(TemporalType.TIMESTAMP) //指定时间格式 45 | @Column(name="insert_time") //指定特定的列名 46 | private java.sql.Timestamp insertTime; 47 | private Geometry polyline; 48 | 49 | public GdNavLink_hibernate() { 50 | super(); 51 | } 52 | 53 | public GdNavLink_hibernate(String dept, Long tmcid, String action, Long distance, 54 | Long duration, Long speed,String orientation, String road, String status, java.sql.Timestamp insertTime, Geometry polyline) { 55 | super(); 56 | this.dept = dept; 57 | this.tmcid = tmcid; 58 | this.action = action; 59 | this.distance = distance; 60 | this.duration = duration; 61 | this.speed = speed; 62 | this.orientation = orientation; 63 | this.road = road; 64 | this.status = status; 65 | this.insertTime = insertTime; 66 | this.polyline = polyline; 67 | } 68 | 69 | 70 | 71 | public Long getSeq() { 72 | return seq; 73 | } 74 | 75 | public void setSeq(Long seq) { 76 | this.seq = seq; 77 | } 78 | 79 | public String getDept() { 80 | return dept; 81 | } 82 | 83 | public void setDept(String dept) { 84 | this.dept = dept; 85 | } 86 | 87 | public Long getTmcid() { 88 | return tmcid; 89 | } 90 | 91 | public void setTmcid(Long tmcid) { 92 | this.tmcid = tmcid; 93 | } 94 | 95 | public String getAction() { 96 | return action; 97 | } 98 | 99 | public void setAction(String action) { 100 | this.action = action; 101 | } 102 | 103 | public Long getDistance() { 104 | return distance; 105 | } 106 | 107 | public void setDistance(Long distance) { 108 | this.distance = distance; 109 | } 110 | 111 | public Long getDuration() { 112 | return duration; 113 | } 114 | 115 | public void setDuration(Long duration) { 116 | this.duration = duration; 117 | } 118 | 119 | public Long getSpeed() { 120 | return speed; 121 | } 122 | 123 | public void setSpeed(Long speed) { 124 | this.speed = speed; 125 | } 126 | 127 | public String getOrientation() { 128 | return orientation; 129 | } 130 | 131 | public void setOrientation(String orientation) { 132 | this.orientation = orientation; 133 | } 134 | 135 | public String getRoad() { 136 | return road; 137 | } 138 | 139 | public void setRoad(String road) { 140 | this.road = road; 141 | } 142 | 143 | public String getStatus() { 144 | return status; 145 | } 146 | 147 | public void setStatus(String status) { 148 | this.status = status; 149 | } 150 | 151 | public java.sql.Timestamp getInsertTime() { 152 | return insertTime; 153 | } 154 | 155 | public void setInsertTime(java.sql.Timestamp insertTime) { 156 | this.insertTime = insertTime; 157 | } 158 | 159 | public Geometry getPolyline() { 160 | return polyline; 161 | } 162 | 163 | public void setPolyline(Geometry polyline) { 164 | this.polyline = polyline; 165 | } 166 | 167 | @Override 168 | public int hashCode() { 169 | return polyline.toText().toString().hashCode(); 170 | } 171 | @Override 172 | public boolean equals(Object o) { 173 | GdNavLink_hibernate p2 = (GdNavLink_hibernate)o; 174 | // 判定条件: 1.geom满足equals关系;2.方向相同 175 | boolean if_equal = polyline.toText().equals(p2.getPolyline().toText()) && 176 | orientation.equals(p2.getOrientation()); 177 | return if_equal; 178 | } 179 | 180 | } 181 | -------------------------------------------------------------------------------- /src/main/java/gaode/GetNav.java: -------------------------------------------------------------------------------- 1 | /* 高德导航,获取路况 2 | * hibernate版本 3 | * 请求示例: 4 | https://restapi.amap.com/v3/direction/driving? 5 | origin=119.363306,26.048199 6 | &destination=119.364579,26.041252 7 | &waypoints=119.2299,26.088477;119.236967,26.091547;119.240965,26.093188 8 | &strategy=10 9 | &extensions=all 10 | &key=你的key 11 | */ 12 | 13 | package gaode; 14 | 15 | import java.util.ArrayList; 16 | import java.util.HashMap; 17 | import java.util.List; 18 | import java.util.Map; 19 | 20 | import org.hibernate.Session; 21 | import org.hibernate.Transaction; 22 | 23 | import com.google.gson.JsonArray; 24 | import com.google.gson.JsonObject; 25 | import com.google.gson.JsonParser; 26 | import com.vividsolutions.jts.geom.Coordinate; 27 | import com.vividsolutions.jts.geom.Geometry; 28 | import com.vividsolutions.jts.io.ParseException; 29 | import com.vividsolutions.jts.io.WKTReader; 30 | 31 | import entity.GdNavLink_hibernate; 32 | import utils.HttpClientResult; 33 | import utils.HttpClientUtils; 34 | import utils.JPAUtil; 35 | 36 | public class GetNav implements Runnable{ 37 | private java.sql.Timestamp insert_time; 38 | private static List links; // 需要导航的OD对 39 | private int linkIndex = 0; // branch11 40 | 41 | public GetNav() { 42 | java.util.Date sysDate = new java.util.Date(); 43 | insert_time = new java.sql.Timestamp(sysDate.getTime()); 44 | }; 45 | 46 | public static void main(String[] args) throws Exception { 47 | GetNav gdrun = new GetNav(); 48 | 49 | int choose = 2; 50 | 51 | if (choose == 1) // 单线程 52 | gdrun.runSingle(); 53 | if (choose == 2) // 多线程 54 | gdrun.runMul(gdrun); 55 | 56 | JPAUtil.close(); 57 | System.out.println("main end.."); 58 | } 59 | 60 | // 多线程接口方法run实现 61 | public void run() { 62 | Session session = JPAUtil.getSession(); 63 | Transaction tx = session.beginTransaction(); 64 | Map link = new HashMap(); 65 | int linkCnt = 0; 66 | 67 | while (true) { 68 | synchronized (this) { 69 | if (linkIndex < links.size()) { 70 | link = links.get(linkIndex); 71 | linkIndex++; 72 | System.out.println("get request: " + linkIndex + "/" + links.size()); 73 | } else { 74 | break; 75 | } 76 | } 77 | // 发送http请求 78 | String content = getHttpReq(link); 79 | if (content == null) 80 | continue; 81 | link.put("content", content); 82 | // 解析返回的内容 83 | List parseList = null; 84 | try { 85 | parseList = parseJson(link); 86 | } catch (ParseException e) { 87 | e.printStackTrace(); 88 | } 89 | if (parseList == null) 90 | continue; 91 | // 保存step和tmc 92 | for (GdNavLink_hibernate gdNavLink : parseList) { 93 | session.save(gdNavLink); 94 | } 95 | 96 | if (++linkCnt % 100 == 0) { // 每N次访问刷新并写入数据库 97 | session.flush(); 98 | session.clear(); 99 | tx.commit(); 100 | tx = session.beginTransaction(); 101 | } 102 | } 103 | session.flush(); 104 | tx.commit(); 105 | session.close(); 106 | } 107 | 108 | // 运行--开了5个线程 109 | public void runMul(GetNav mulThread) throws InterruptedException { 110 | // 获取所有request 111 | links = getLinks(); 112 | Thread t1 = new Thread(mulThread); 113 | Thread t2 = new Thread(mulThread); 114 | Thread t3 = new Thread(mulThread); 115 | Thread t4 = new Thread(mulThread); 116 | Thread t5 = new Thread(mulThread); 117 | t1.start(); 118 | t2.start(); 119 | t3.start(); 120 | t4.start(); 121 | t5.start(); 122 | t1.join(); 123 | t2.join(); 124 | t3.join(); 125 | t4.join(); 126 | t5.join(); 127 | } 128 | 129 | // 运行--单线程 130 | public void runSingle() throws Exception { 131 | Session session = JPAUtil.getSession(); 132 | Transaction tx = session.beginTransaction(); 133 | 134 | // 获取所有request 135 | links = getLinks(); 136 | // 逐条处理: 发送请求/解析/保存 137 | for (int i = 0; i < links.size(); i++) { 138 | Map link = links.get(i); 139 | System.out.println("get response:" + (i + 1) + "/" + links.size()); 140 | // 发送http请求 141 | String content = getHttpReq(link); 142 | if (content == null) 143 | continue; 144 | link.put("content", content); 145 | // 解析返回的内容 146 | List parseList = parseJson(link); 147 | if (parseList == null) 148 | continue; 149 | // 保存step和tmc 150 | for (GdNavLink_hibernate gdNavLink : parseList) { 151 | session.save(gdNavLink); 152 | } 153 | if (i % 50 == 49) { 154 | session.flush(); 155 | session.clear(); 156 | } 157 | } 158 | tx.commit(); 159 | session.close(); 160 | } 161 | 162 | // 1获取导航OD对 163 | public static List getLinks() { 164 | Session session = JPAUtil.getSession(); 165 | List objects = session.createSQLQuery("SELECT * FROM V_GD_NAV_POINT").addScalar("s").addScalar("e").list(); 166 | session.clear(); 167 | session.close(); 168 | 169 | Map map = new HashMap(); 170 | List linkList = new ArrayList(); 171 | for (Object[] obj : objects) { 172 | map = new HashMap(); 173 | map.put("S", obj[0]); 174 | map.put("E", obj[1]); 175 | linkList.add(map); 176 | } 177 | System.out.println("待解析的OD数: " + linkList.size()); 178 | return linkList; 179 | } 180 | 181 | // 2发起请求 182 | public String getHttpReq(Map map) { 183 | String url = "https://restapi.amap.com/v3/direction/driving"; 184 | Map params = new HashMap(); 185 | params.put("key", "你的key"); 186 | params.put("extensions", "all"); 187 | params.put("strategy", "10"); //10默认多路径;2单路径,距离最短 188 | params.put("origin", (String) map.get("S")); 189 | params.put("destination", (String) map.get("E")); 190 | 191 | HttpClientResult result; 192 | try { 193 | result = HttpClientUtils.doGet(url, params); 194 | } catch (Exception e) { 195 | System.out.println("访问接口出错了,忽略本次请求..."); 196 | return null; 197 | } 198 | 199 | // 访问API失败 200 | if (result.getCode() != 200) { 201 | System.out.println("访问API失败: " + result.getCode()); 202 | return null; 203 | } 204 | // 访问成功 205 | return result.getContent(); 206 | } 207 | 208 | // 3json解析返回值 209 | public List parseJson(Map linkContent) throws ParseException { 210 | JsonParser parser = new JsonParser(); 211 | JsonObject obj = (JsonObject) parser.parse((String) linkContent.get("content")); 212 | 213 | // 导航是否成功,处理失败的情景 214 | int status = 0, count = 0; 215 | if (obj.get("status") != null) { 216 | status = obj.get("status").getAsInt(); 217 | } 218 | if (obj.get("count") != null) { 219 | count = obj.get("count").getAsInt(); 220 | } 221 | String info = obj.get("info").getAsString(); 222 | // 无效导航 223 | if (status == 0 || count == 0) { 224 | System.out.println("response none..; info:" + info); 225 | return null; 226 | } 227 | // 有效导航,开始处理 228 | String orientation, road, action, polyline, linkStatus; 229 | Long tmcid, distance, duration,speed; 230 | GdNavLink_hibernate singleLink; 231 | List list = new ArrayList(); 232 | 233 | JsonArray paths = obj.get("route").getAsJsonObject().get("paths").getAsJsonArray(); 234 | // System.out.print("paths:" + paths.size() + "; "); 235 | // 逐一处理paths (paths即为多个方案, 每个方案中有多个steps) 236 | for (int pid = 0; pid < paths.size(); pid++) { 237 | List stepList = new ArrayList(); 238 | JsonArray steps = paths.get(pid).getAsJsonObject().get("steps").getAsJsonArray(); 239 | // System.out.print("steps:" + steps.size() + "; tmcs:"); 240 | // 逐一处理steps 241 | for (int i = 0; i < steps.size(); i++) { 242 | orientation = ""; 243 | road = ""; 244 | action = ""; 245 | linkStatus = ""; 246 | polyline = ""; 247 | Geometry geom = null; 248 | singleLink = null; 249 | tmcid = 0L; 250 | distance = -1L; 251 | duration = -1L; 252 | speed = -1L; 253 | 254 | JsonObject step = steps.get(i).getAsJsonObject(); 255 | if (step.get("orientation") != null) { 256 | orientation = step.get("orientation").getAsString(); 257 | } 258 | if (step.get("road") != null) { 259 | road = step.get("road").getAsString(); 260 | } 261 | if (step.get("action") != null) { 262 | if (!step.get("action").isJsonArray()) 263 | action = step.get("action").getAsString(); 264 | } 265 | if (step.get("distance") != null && step.get("duration") != null) { 266 | distance = step.get("distance").getAsLong(); 267 | duration = step.get("duration").getAsLong(); 268 | speed = new Double(distance*3.6/duration).longValue(); 269 | } 270 | if (step.get("polyline") != null) { 271 | polyline = step.get("polyline").getAsString(); 272 | polyline = polyline.replace(",", " "); 273 | polyline = polyline.replace(";", ","); 274 | WKTReader fromText = new WKTReader(); 275 | geom = fromText.read("LINESTRING(" + polyline + ")"); 276 | geom.setSRID(4326); 277 | } 278 | singleLink = new GdNavLink_hibernate("step", (Long) tmcid, action, (Long) distance, (Long) duration,speed,orientation, road, linkStatus, insert_time, geom); 279 | list.add(singleLink); 280 | stepList.add(singleLink); 281 | 282 | // 循环处理tmcs 283 | JsonArray tmcs = step.get("tmcs").getAsJsonArray(); 284 | // System.out.print(tmcs.size() + ","); 285 | for (int j = 0; j < tmcs.size(); j++) { 286 | 287 | // 第一个step的第一个tmc忽略 288 | if (i == 0 && j == 0) { 289 | continue; 290 | } 291 | // 最后一个step的最后一个tmc忽略 292 | if (i == (steps.size() - 1) && j == (tmcs.size() - 1)) { 293 | continue; 294 | } 295 | 296 | tmcid++; 297 | distance = -1L; 298 | linkStatus = ""; 299 | polyline = ""; 300 | singleLink = null; 301 | 302 | JsonObject tmc = tmcs.get(j).getAsJsonObject(); 303 | if (tmc.get("distance") != null) { 304 | distance = tmc.get("distance").getAsLong(); 305 | } 306 | if (tmc.get("status") != null) { 307 | linkStatus = tmc.get("status").getAsString(); 308 | } 309 | if (tmc.get("polyline") != null) { 310 | polyline = tmc.get("polyline").getAsString(); 311 | polyline = polyline.replace(",", " "); 312 | polyline = polyline.replace(";", ","); 313 | WKTReader fromText = new WKTReader(); 314 | geom = fromText.read("LINESTRING(" + polyline + ")"); 315 | geom.setSRID(4326); 316 | } 317 | //速度直接取step的速度,当step较长时,tmc的速度误差大 318 | singleLink = new GdNavLink_hibernate("tmc", tmcid, action, distance, -1L,speed, orientation, road, 319 | linkStatus, insert_time, geom); 320 | list.add(singleLink); 321 | } 322 | } 323 | 324 | // 额外补充: 如果两个step之间断开,则额外补充一条线将两者相连 325 | for (int i = 0; i < stepList.size() - 1; i++) { 326 | Coordinate pointLast = stepList.get(i).getPolyline() 327 | .getCoordinates()[stepList.get(i).getPolyline().getNumPoints() - 1]; 328 | Coordinate pointFirst = stepList.get(i + 1).getPolyline().getCoordinates()[0]; 329 | if (pointLast.equals2D(pointFirst)) { 330 | continue; 331 | } 332 | String addLine = pointLast.x + " " + pointLast.y + "," + pointFirst.x + " " + pointFirst.y; 333 | WKTReader fromText = new WKTReader(); 334 | Geometry geom = fromText.read("LINESTRING(" + addLine + ")"); 335 | geom.setSRID(4326); 336 | list.add(new GdNavLink_hibernate("tmc", -1L, "手动补线", -1L, -1L, -1L, stepList.get(i).getOrientation(), 337 | stepList.get(i).getRoad(), "", insert_time, geom)); 338 | } 339 | 340 | } 341 | return list; 342 | } 343 | 344 | 345 | } 346 | -------------------------------------------------------------------------------- /src/main/java/gaode/GetNavNJ.java: -------------------------------------------------------------------------------- 1 | package gaode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Date; 5 | import java.util.HashMap; 6 | import java.util.HashSet; 7 | import java.util.List; 8 | import java.util.Map; 9 | 10 | import org.hibernate.Session; 11 | import org.hibernate.Transaction; 12 | import org.hibernate.type.LongType; 13 | 14 | import com.google.gson.JsonArray; 15 | import com.google.gson.JsonObject; 16 | import com.google.gson.JsonParser; 17 | import com.vividsolutions.jts.geom.Coordinate; 18 | import com.vividsolutions.jts.geom.Geometry; 19 | import com.vividsolutions.jts.io.ParseException; 20 | import com.vividsolutions.jts.io.WKTReader; 21 | 22 | import entity.GdNavLinkNJ; 23 | import utils.HttpClientResult; 24 | import utils.HttpClientUtils; 25 | import utils.JPAUtil; 26 | 27 | public class GetNavNJ { 28 | private java.sql.Timestamp insert_time; 29 | private List links; // 需要导航的OD对 30 | private Long batch; 31 | private List tlist = new ArrayList(); 32 | 33 | public GetNavNJ() { 34 | java.util.Date sysDate = new java.util.Date(); 35 | insert_time = new java.sql.Timestamp(sysDate.getTime()); 36 | }; 37 | 38 | public static void main(String[] args) throws Exception { 39 | GetNavNJ gdrun = new GetNavNJ(); 40 | gdrun.runSingle(); 41 | System.out.println("main end.."); 42 | } 43 | 44 | // 运行--单线程 45 | public void runSingle() throws Exception { 46 | Session session = JPAUtil.getSession(); 47 | Transaction tx = session.beginTransaction(); 48 | 49 | // 获取所有request 50 | links = getLinks(); 51 | // 获取该次导航的batch 52 | batch = getBatch(); 53 | 54 | // 逐条处理: 发送请求;解析 55 | for (int i = 0; i < links.size(); i++) { 56 | Map link = links.get(i); 57 | System.out.println("get response:" + (i + 1) + "/" + links.size()); 58 | // 发送http请求 59 | String content = getHttpReq(link); 60 | if (content == null) 61 | continue; 62 | link.put("content", content); 63 | // 解析返回的内容 64 | parseJson(link); 65 | } 66 | 67 | // 删除重复 68 | delDump(); 69 | 70 | // 为新数据赋值linkid 71 | setLinkid(); 72 | 73 | //保存数据 74 | for (GdNavLinkNJ gdNavLink : tlist) { 75 | session.save(gdNavLink); 76 | } 77 | 78 | session.flush(); 79 | session.clear(); 80 | tx.commit(); 81 | session.close(); 82 | JPAUtil.close(); 83 | System.out.println("batch: " + batch + " " + new Date()); 84 | } 85 | 86 | 87 | // 1获取导航OD对 88 | public List getLinks() { 89 | Session session = JPAUtil.getSession(); 90 | List objects = session.createSQLQuery("SELECT * FROM V_GD_NAV_ROAD").addScalar("s").addScalar("e") 91 | .addScalar("m").list(); 92 | session.clear(); 93 | session.close(); 94 | 95 | Map map = new HashMap(); 96 | List linkList = new ArrayList(); 97 | for (Object[] obj : objects) { 98 | map = new HashMap(); 99 | map.put("S", obj[0]); 100 | map.put("E", obj[1]); 101 | map.put("M", obj[2]); 102 | linkList.add(map); 103 | } 104 | System.out.println("待解析的OD数: " + linkList.size()); 105 | return linkList; 106 | } 107 | 108 | // 2发起请求 109 | public String getHttpReq(Map map) { 110 | String url = "https://restapi.amap.com/v3/direction/driving"; 111 | Map params = new HashMap(); 112 | params.put("key", "你的key"); 113 | params.put("extensions", "all"); 114 | params.put("strategy", "2"); // 10默认多路径;2单路径,距离最短 115 | params.put("origin", (String) map.get("S")); 116 | params.put("destination", (String) map.get("E")); 117 | // 中途点 118 | params.put("waypoints", (String) map.get("M")); 119 | 120 | HttpClientResult result; 121 | try { 122 | result = HttpClientUtils.doGet(url, params); 123 | } catch (Exception e) { 124 | System.out.println("访问接口出错了,忽略本次请求..."); 125 | return null; 126 | } 127 | 128 | // 访问API失败 129 | if (result.getCode() != 200) { 130 | System.out.println("访问API失败: " + result.getCode()); 131 | return null; 132 | } 133 | // 访问成功 134 | return result.getContent(); 135 | } 136 | 137 | // 3json解析返回值 138 | public void parseJson(Map linkContent) throws ParseException { 139 | JsonParser parser = new JsonParser(); 140 | JsonObject obj = (JsonObject) parser.parse((String) linkContent.get("content")); 141 | 142 | // 导航是否成功,处理失败的情景 143 | int status = 0, count = 0; 144 | if (obj.get("status") != null) { 145 | status = obj.get("status").getAsInt(); 146 | } 147 | if (obj.get("count") != null) { 148 | count = obj.get("count").getAsInt(); 149 | } 150 | String info = obj.get("info").getAsString(); 151 | // 无效导航 152 | if (status == 0 || count == 0) { 153 | System.out.println("response none..; info:" + info); 154 | return; 155 | } 156 | // 有效导航,开始处理 157 | String orientation, road, action, polyline, linkStatus; 158 | Long tmcid, distance, duration, speed; 159 | GdNavLinkNJ singleLink; 160 | List list = new ArrayList(); 161 | 162 | JsonArray paths = obj.get("route").getAsJsonObject().get("paths").getAsJsonArray(); 163 | // System.out.print("paths:" + paths.size() + "; "); 164 | // 逐一处理paths (paths即为多个方案, 每个方案中有多个steps) 165 | for (int pid = 0; pid < paths.size(); pid++) { 166 | JsonArray steps = paths.get(pid).getAsJsonObject().get("steps").getAsJsonArray(); 167 | // System.out.print("steps:" + steps.size() + "; tmcs:"); 168 | // 逐一处理steps 169 | for (int i = 0; i < steps.size(); i++) { 170 | orientation = ""; 171 | road = ""; 172 | action = ""; 173 | linkStatus = ""; 174 | polyline = ""; 175 | Geometry geom = null; 176 | singleLink = null; 177 | tmcid = 0L; 178 | distance = -1L; 179 | duration = -1L; 180 | speed = -1L; 181 | 182 | JsonObject step = steps.get(i).getAsJsonObject(); 183 | if (step.get("orientation") != null) { 184 | orientation = step.get("orientation").getAsString(); 185 | } 186 | if (step.get("road") != null) { 187 | road = step.get("road").getAsString(); 188 | } 189 | if (step.get("action") != null) { 190 | if (!step.get("action").isJsonArray()) 191 | action = step.get("action").getAsString(); 192 | } 193 | if (step.get("distance") != null && step.get("duration") != null) { 194 | distance = step.get("distance").getAsLong(); 195 | duration = step.get("duration").getAsLong(); 196 | speed = new Double(distance * 3.6 / duration).longValue(); 197 | } 198 | if (step.get("polyline") != null) { 199 | polyline = step.get("polyline").getAsString(); 200 | polyline = polyline.replace(",", " "); 201 | polyline = polyline.replace(";", ","); 202 | WKTReader fromText = new WKTReader(); 203 | geom = fromText.read("LINESTRING(" + polyline + ")"); 204 | geom.setSRID(4326); 205 | } 206 | // singleLink = new GdNavLinkNJ("step", (Long) tmcid, action, (Long) 207 | // distance, (Long) duration,speed,orientation, road, linkStatus, insert_time, 208 | // geom); 209 | // list.add(singleLink); 210 | 211 | // 循环处理tmcs 212 | JsonArray tmcs = step.get("tmcs").getAsJsonArray(); 213 | // System.out.print(tmcs.size() + ","); 214 | for (int j = 0; j < tmcs.size(); j++) { 215 | /* 216 | * // 第一个step的第一个tmc忽略 if (i == 0 && j == 0) { continue; } // 最后一个step的最后一个tmc忽略 217 | * if (i == (steps.size() - 1) && j == (tmcs.size() - 1)) { continue; } 218 | */ 219 | tmcid++; 220 | distance = -1L; 221 | linkStatus = ""; 222 | polyline = ""; 223 | singleLink = null; 224 | 225 | JsonObject tmc = tmcs.get(j).getAsJsonObject(); 226 | if (tmc.get("distance") != null) { 227 | distance = tmc.get("distance").getAsLong(); 228 | if (distance < 3L) 229 | continue; 230 | } 231 | if (tmc.get("status") != null) { 232 | linkStatus = tmc.get("status").getAsString(); 233 | } 234 | if (tmc.get("polyline") != null) { 235 | polyline = tmc.get("polyline").getAsString(); 236 | polyline = polyline.replace(",", " "); 237 | polyline = polyline.replace(";", ","); 238 | WKTReader fromText = new WKTReader(); 239 | geom = fromText.read("LINESTRING(" + polyline + ")"); 240 | geom.setSRID(4326); 241 | } 242 | // 速度直接取step的速度 243 | singleLink = new GdNavLinkNJ(batch,null,"tmc", tmcid, action, distance, -1L, speed, orientation, road, 244 | linkStatus, insert_time, geom); 245 | list.add(singleLink); 246 | } 247 | } 248 | } 249 | tlist.addAll(list); 250 | } 251 | 252 | // 取循环标识 batch, 从oracle中的序列SEQ_GD_NAV_NJ取 253 | public Long getBatch() { 254 | Session session = JPAUtil.getSession(); 255 | Long batch = (Long)session.createSQLQuery("select SEQ_GD_NAV_NJ.nextval from dual").addScalar("nextval", LongType.INSTANCE).uniqueResult(); 256 | session.close(); 257 | return batch; 258 | } 259 | 260 | // 删除重复. 已在GdNavLinkNJ中定义何为重复 261 | public void delDump() { 262 | HashSet tset = new HashSet(); 263 | tset.addAll(tlist); 264 | tlist.removeAll(tlist); 265 | tlist.addAll(tset); 266 | } 267 | 268 | // 为新数据赋值linkid 269 | public void setLinkid() { 270 | //取基准linkList 271 | Session session = JPAUtil.getSession(); 272 | List baseLinks = session.createQuery("from GdNavLinkNJ t where t.batch = 0").list(); 273 | session.close(); 274 | //更新新数据 275 | for(int i = 0;i 获得全新session 18 | public static Session openSession() { 19 | // 3 获得session 20 | Session session = sf.openSession(); 21 | return session; 22 | 23 | } 24 | 25 | // 获得session => 获得与线程绑定的session 26 | public static Session getCurrentSession() { 27 | // 3 获得session 28 | Session session = sf.getCurrentSession(); 29 | return session; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/utils/HttpClientResult.java: -------------------------------------------------------------------------------- 1 | package utils; 2 | 3 | public class HttpClientResult { 4 | 5 | private int code; //响应状态码 6 | private String content; //响应数据 7 | 8 | public HttpClientResult(int code) { 9 | super(); 10 | this.code = code; 11 | } 12 | 13 | public HttpClientResult(int code, String content) { 14 | super(); 15 | this.code = code; 16 | this.content = content; 17 | } 18 | 19 | public int getCode() { 20 | return code; 21 | } 22 | 23 | public String getContent() { 24 | return content; 25 | } 26 | 27 | public String toString() { 28 | String result = "code: "+ code + "; " + "content: " + content; 29 | return result ; 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/java/utils/HttpClientUtils.java: -------------------------------------------------------------------------------- 1 | package utils; 2 | 3 | import java.io.IOException; 4 | import java.io.UnsupportedEncodingException; 5 | import java.util.ArrayList; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | import java.util.Map; 9 | import java.util.Map.Entry; 10 | import java.util.Set; 11 | 12 | import org.apache.http.HttpStatus; 13 | import org.apache.http.NameValuePair; 14 | import org.apache.http.client.config.RequestConfig; 15 | import org.apache.http.client.entity.UrlEncodedFormEntity; 16 | import org.apache.http.client.methods.CloseableHttpResponse; 17 | import org.apache.http.client.methods.HttpDelete; 18 | import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; 19 | import org.apache.http.client.methods.HttpGet; 20 | import org.apache.http.client.methods.HttpPost; 21 | import org.apache.http.client.methods.HttpPut; 22 | import org.apache.http.client.methods.HttpRequestBase; 23 | import org.apache.http.client.utils.URIBuilder; 24 | import org.apache.http.impl.client.CloseableHttpClient; 25 | import org.apache.http.impl.client.HttpClients; 26 | import org.apache.http.message.BasicNameValuePair; 27 | import org.apache.http.util.EntityUtils; 28 | 29 | public class HttpClientUtils { 30 | 31 | // 编码格式。发送编码格式统一用UTF-8 32 | private static final String ENCODING = "UTF-8"; 33 | // 设置连接超时时间,单位毫秒。 34 | private static final int CONNECT_TIMEOUT = 6000; 35 | // 请求获取数据的超时时间(即响应时间),单位毫秒。 36 | private static final int SOCKET_TIMEOUT = 6000; 37 | 38 | /** 39 | * 发送get请求;不带请求头和请求参数 40 | * 41 | * @param url 请求地址 42 | * @return 43 | * @throws Exception 44 | */ 45 | public static HttpClientResult doGet(String url) throws Exception { 46 | return doGet(url, null, null); 47 | } 48 | 49 | /** 50 | * 发送get请求;带请求参数 51 | * 52 | * @param url 请求地址 53 | * @param params 请求参数集合 54 | * @return 55 | * @throws Exception 56 | */ 57 | public static HttpClientResult doGet(String url, Map params) throws Exception { 58 | return doGet(url, null, params); 59 | } 60 | 61 | /** 62 | * 发送get请求;带请求头和请求参数 63 | * 64 | * @param url 请求地址 65 | * @param headers 请求头集合 66 | * @param params 请求参数集合 67 | * @return 68 | * @throws Exception 69 | */ 70 | public static HttpClientResult doGet(String url, Map headers, Map params) throws Exception { 71 | // 创建httpClient对象 72 | CloseableHttpClient httpClient = HttpClients.createDefault(); 73 | 74 | // 创建访问的地址 75 | URIBuilder uriBuilder = new URIBuilder(url); 76 | if (params != null) { 77 | Set> entrySet = params.entrySet(); 78 | for (Entry entry : entrySet) { 79 | uriBuilder.setParameter(entry.getKey(), entry.getValue()); 80 | } 81 | } 82 | 83 | // 创建http对象 84 | HttpGet httpGet = new HttpGet(uriBuilder.build()); 85 | /** 86 | * setConnectTimeout:设置连接超时时间,单位毫秒。 87 | * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection 88 | * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。 89 | * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 90 | */ 91 | RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); 92 | httpGet.setConfig(requestConfig); 93 | 94 | // 设置请求头 95 | packageHeader(headers, httpGet); 96 | 97 | // 创建httpResponse对象 98 | CloseableHttpResponse httpResponse = null; 99 | 100 | try { 101 | // 执行请求并获得响应结果 102 | return getHttpClientResult(httpResponse, httpClient, httpGet); 103 | } finally { 104 | // 释放资源 105 | release(httpResponse, httpClient); 106 | } 107 | } 108 | 109 | /** 110 | * 发送post请求;不带请求头和请求参数 111 | * 112 | * @param url 请求地址 113 | * @return 114 | * @throws Exception 115 | */ 116 | public static HttpClientResult doPost(String url) throws Exception { 117 | return doPost(url, null, null); 118 | } 119 | 120 | /** 121 | * 发送post请求;带请求参数 122 | * 123 | * @param url 请求地址 124 | * @param params 参数集合 125 | * @return 126 | * @throws Exception 127 | */ 128 | public static HttpClientResult doPost(String url, Map params) throws Exception { 129 | return doPost(url, null, params); 130 | } 131 | 132 | /** 133 | * 发送post请求;带请求头和请求参数 134 | * 135 | * @param url 请求地址 136 | * @param headers 请求头集合 137 | * @param params 请求参数集合 138 | * @return 139 | * @throws Exception 140 | */ 141 | public static HttpClientResult doPost(String url, Map headers, Map params) throws Exception { 142 | // 创建httpClient对象 143 | CloseableHttpClient httpClient = HttpClients.createDefault(); 144 | 145 | // 创建http对象 146 | HttpPost httpPost = new HttpPost(url); 147 | /** 148 | * setConnectTimeout:设置连接超时时间,单位毫秒。 149 | * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection 150 | * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。 151 | * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 152 | */ 153 | RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); 154 | httpPost.setConfig(requestConfig); 155 | // 设置请求头 156 | /*httpPost.setHeader("Cookie", ""); 157 | httpPost.setHeader("Connection", "keep-alive"); 158 | httpPost.setHeader("Accept", "application/json"); 159 | httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9"); 160 | httpPost.setHeader("Accept-Encoding", "gzip, deflate, br"); 161 | httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/ 162 | packageHeader(headers, httpPost); 163 | 164 | // 封装请求参数 165 | packageParam(params, httpPost); 166 | 167 | // 创建httpResponse对象 168 | CloseableHttpResponse httpResponse = null; 169 | 170 | try { 171 | // 执行请求并获得响应结果 172 | return getHttpClientResult(httpResponse, httpClient, httpPost); 173 | } finally { 174 | // 释放资源 175 | release(httpResponse, httpClient); 176 | } 177 | } 178 | 179 | /** 180 | * 发送put请求;不带请求参数 181 | * 182 | * @param url 请求地址 183 | * @param params 参数集合 184 | * @return 185 | * @throws Exception 186 | */ 187 | public static HttpClientResult doPut(String url) throws Exception { 188 | return doPut(url); 189 | } 190 | 191 | /** 192 | * 发送put请求;带请求参数 193 | * 194 | * @param url 请求地址 195 | * @param params 参数集合 196 | * @return 197 | * @throws Exception 198 | */ 199 | public static HttpClientResult doPut(String url, Map params) throws Exception { 200 | CloseableHttpClient httpClient = HttpClients.createDefault(); 201 | HttpPut httpPut = new HttpPut(url); 202 | RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); 203 | httpPut.setConfig(requestConfig); 204 | 205 | packageParam(params, httpPut); 206 | 207 | CloseableHttpResponse httpResponse = null; 208 | 209 | try { 210 | return getHttpClientResult(httpResponse, httpClient, httpPut); 211 | } finally { 212 | release(httpResponse, httpClient); 213 | } 214 | } 215 | 216 | /** 217 | * 发送delete请求;不带请求参数 218 | * 219 | * @param url 请求地址 220 | * @param params 参数集合 221 | * @return 222 | * @throws Exception 223 | */ 224 | public static HttpClientResult doDelete(String url) throws Exception { 225 | CloseableHttpClient httpClient = HttpClients.createDefault(); 226 | HttpDelete httpDelete = new HttpDelete(url); 227 | RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build(); 228 | httpDelete.setConfig(requestConfig); 229 | 230 | CloseableHttpResponse httpResponse = null; 231 | try { 232 | return getHttpClientResult(httpResponse, httpClient, httpDelete); 233 | } finally { 234 | release(httpResponse, httpClient); 235 | } 236 | } 237 | 238 | /** 239 | * 发送delete请求;带请求参数 240 | * 241 | * @param url 请求地址 242 | * @param params 参数集合 243 | * @return 244 | * @throws Exception 245 | */ 246 | public static HttpClientResult doDelete(String url, Map params) throws Exception { 247 | if (params == null) { 248 | params = new HashMap(); 249 | } 250 | 251 | params.put("_method", "delete"); 252 | return doPost(url, params); 253 | } 254 | 255 | /** 256 | * Description: 封装请求头 257 | * @param params 258 | * @param httpMethod 259 | */ 260 | public static void packageHeader(Map params, HttpRequestBase httpMethod) { 261 | // 封装请求头 262 | if (params != null) { 263 | Set> entrySet = params.entrySet(); 264 | for (Entry entry : entrySet) { 265 | // 设置到请求头到HttpRequestBase对象中 266 | httpMethod.setHeader(entry.getKey(), entry.getValue()); 267 | } 268 | } 269 | } 270 | 271 | /** 272 | * Description: 封装请求参数 273 | * 274 | * @param params 275 | * @param httpMethod 276 | * @throws UnsupportedEncodingException 277 | */ 278 | public static void packageParam(Map params, HttpEntityEnclosingRequestBase httpMethod) 279 | throws UnsupportedEncodingException { 280 | // 封装请求参数 281 | if (params != null) { 282 | List nvps = new ArrayList(); 283 | Set> entrySet = params.entrySet(); 284 | for (Entry entry : entrySet) { 285 | nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); 286 | } 287 | 288 | // 设置到请求的http对象中 289 | httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING)); 290 | } 291 | } 292 | 293 | /** 294 | * Description: 获得响应结果 295 | * 296 | * @param httpResponse 297 | * @param httpClient 298 | * @param httpMethod 299 | * @return 300 | * @throws Exception 301 | */ 302 | public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse, 303 | CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception { 304 | // 执行请求 305 | httpResponse = httpClient.execute(httpMethod); 306 | 307 | // 获取返回结果 308 | if (httpResponse != null && httpResponse.getStatusLine() != null) { 309 | String content = ""; 310 | if (httpResponse.getEntity() != null) { 311 | content = EntityUtils.toString(httpResponse.getEntity(), ENCODING); 312 | } 313 | return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content); 314 | } 315 | return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR); 316 | } 317 | 318 | /** 319 | * Description: 释放资源 320 | * 321 | * @param httpResponse 322 | * @param httpClient 323 | * @throws IOException 324 | */ 325 | public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException { 326 | // 释放资源 327 | if (httpResponse != null) { 328 | httpResponse.close(); 329 | } 330 | if (httpClient != null) { 331 | httpClient.close(); 332 | } 333 | } 334 | 335 | } -------------------------------------------------------------------------------- /src/main/java/utils/JPAUtil.java: -------------------------------------------------------------------------------- 1 | package utils; 2 | 3 | import javax.persistence.EntityManager; 4 | import javax.persistence.EntityManagerFactory; 5 | import javax.persistence.Persistence; 6 | 7 | import org.hibernate.Session; 8 | 9 | public class JPAUtil { 10 | private static final EntityManagerFactory emFactory; 11 | 12 | static { 13 | try { 14 | emFactory = Persistence.createEntityManagerFactory("SPATIAL-JPA"); 15 | }catch(Throwable ex){ 16 | System.err.println("Cannot create EntityManagerFactory."); 17 | throw new ExceptionInInitializerError(ex); 18 | } 19 | } 20 | 21 | public static EntityManager createEntityManager() { 22 | return emFactory.createEntityManager(); 23 | } 24 | 25 | public static void close(){ 26 | emFactory.close(); 27 | } 28 | //为了在JPA环境中使用hibernate API,此步骤获取hiber原生session 29 | public static Session getSession() { 30 | //EntityManager em = JPAUtil.createEntityManager(); 31 | //Session session = em.unwrap(Session.class); 32 | return emFactory.createEntityManager().unwrap(Session.class); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/persistence.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | Persistence unit for the JPA Hibernate Spatial Tutorial 10 | 11 | 12 | 13 | entity.GdNavLink_hibernate 14 | entity.GdNavLinkNJ 15 | true 16 | 17 | 18 | 19 | 21 | 22 | 24 | 25 | 27 | 28 | 29 | 30 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /src/test/java/gaode/TestClass.java: -------------------------------------------------------------------------------- 1 | package gaode; 2 | 3 | import org.junit.Test; 4 | 5 | public class TestClass { 6 | 7 | @Test 8 | public void tttt() { 9 | System.out.println("testing.."); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /target/classes/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Built-By: xu_xk 3 | Build-Jdk: 1.8.0_191 4 | Created-By: Maven Integration for Eclipse 5 | 6 | --------------------------------------------------------------------------------