mysql数据库建表:
/*
Navicat Premium Data Transfer
Source Server : DKZH
Source Server Type : MySQL
Source Server Version : 80025
Source Host : 8.142.83.87:3310
Source Schema : platform_admin
Target Server Type : MySQL
Target Server Version : 80025
File Encoding : 65001
Date: 18/02/2022 17:47:58
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for sys_district_gd
-- ----------------------------
DROP TABLE IF EXISTS `sys_district_gd`;
CREATE TABLE `sys_district_gd` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键id',
`ad_code` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '区域编码 街道没有独有的adcode,均继承父类(区县)的adcode',
`name` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '名称',
`level` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '等级 国家(country) 省(province) 市(city) 区/县(district)',
`city_code` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '城市代码',
`parent_code` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '父类代码',
`parent_name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '父类名称',
`full_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '全称',
`longitude` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '经度',
`latitude` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '纬度',
`gmt_create` timestamp(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '创建时间',
`gmt_modify` timestamp(0) NULL DEFAULT NULL COMMENT '最后修改时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3658 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '高德地图 省市县' ROW_FORMAT = COMPACT;
SET FOREIGN_KEY_CHECKS = 1;
entity层:
package com.king.common.entity.business;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
@TableName(value = "sys_district_gd")
public class GaoDeDistrict implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;//主键ID
@TableField(value = "ad_code")
private String adCode;//区域编码
@TableField(value = "name")
private String name;//名称
@TableField(value = "level")
private String level;//等级 国家(country) 省(province) 市(city) 区/县(district)
@TableField(value = "city_code")
private String cityCode;//城市代码
@TableField(value = "parent_code")
private String parentCode;//父类代码
@TableField(value = "parent_name")
private String parentName;//父类名称
@TableField(value = "full_name")
private String fullName;//全称
@TableField(value = "longitude")
private String longitude;//经度
@TableField(value = "latitude")
private String latitude;//纬度
@TableField(value = "gmt_create")
private Date gmtCreate;//创建时间
@TableField(value = "gmt_modify")
private Date gmtModify;//最后修改时间
public GaoDeDistrict() {
}
@Override
public String toString() {
return "GaoDeDistrict{" +
"id=" + id +
", adCode='" + adCode + '\'' +
", name='" + name + '\'' +
", level='" + level + '\'' +
", cityCode='" + cityCode + '\'' +
", parentCode='" + parentCode + '\'' +
", parentName='" + parentName + '\'' +
", fullName='" + fullName + '\'' +
", longitude='" + longitude + '\'' +
", latitude='" + latitude + '\'' +
", gmtCreate='" + gmtCreate + '\'' +
", gmtModify='" + gmtModify + '\'' +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAdCode() {
return adCode;
}
public void setAdCode(String adCode) {
this.adCode = adCode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getParentCode() {
return parentCode;
}
public void setParentCode(String parentCode) {
this.parentCode = parentCode;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModify() {
return gmtModify;
}
public void setGmtModify(Date gmtModify) {
this.gmtModify = gmtModify;
}
}
mapper层:
package com.king.common.web.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface AbstractMapper<T> extends BaseMapper<T> {
}
package com.king.biz.mapper;
import com.king.common.entity.business.GaoDeDistrict;
import com.king.common.web.mapper.AbstractMapper;
public interface GaoDeDistrictMapper extends AbstractMapper<GaoDeDistrict> {
}
Service层:
package com.king.biz.service;
import com.king.biz.mapper.GaoDeDistrictMapper;
import com.king.common.entity.business.GaoDeDistrict;
import com.king.common.web.service.impl.AbstractServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional(rollbackFor = Exception.class)
public class GaoDeDistrictService extends AbstractServiceImpl<GaoDeDistrictMapper, GaoDeDistrict> {
}
Controller:
package com.king.biz.rest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.king.auth.client.annotation.IgnoreClientToken;
import com.king.auth.client.annotation.IgnoreUserToken;
import com.king.biz.service.GaoDeDistrictService;
import com.king.common.entity.business.GaoDeDistrict;
import com.king.common.util.HttpRequestUtil;
import com.king.common.web.controller.AbstractSpringController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("business/GaoDeDistrict")
@IgnoreClientToken
@IgnoreUserToken
public class GaoDeDistrictController extends AbstractSpringController<GaoDeDistrict, GaoDeDistrictService> {
//调用高德api获取数据存到数据库中
@PostMapping("/getGaoDeDistrict")
public Object getGaoDeDistrict() throws Exception {
String s = new HttpRequestUtil().doGetRequest("https://restapi.amap.com/v3/config/district?subdistrict=3&key=02154c1b8927a3dbd8c5ca0f44ccdd6b");
JSONObject json = JSONObject.parseObject(s);
int count = 0;
System.out.println(json.get("status"));
//List<String> list = new ArrayList<>();
//Map<String, Object> provinceMap = new HashMap<String, Object>();
if (json.get("status").equals("1")) {
//国家 暂时只有中国
JSONArray districts = json.getJSONArray("districts");
for (int i = 0; i < districts.size(); i++) {
JSONObject district = districts.getJSONObject(i);
//省份
JSONArray provinces = district.getJSONArray("districts");
for (int j = 0; j < provinces.size(); j++) {
JSONObject province = provinces.getJSONObject(j);
String provinceCenter = province.getString("center");
String[] provinceCenterSplit = provinceCenter.split(",");
// System.out.println(
// "province :::::: ==== name:" + province.getString("name") +
// " center:" + province.getString("center") +
// " longitude:" + provinceCenterSplit[0] + " latitude:" + provinceCenterSplit[1] +
// " adcode:" + province.getString("adcode") +
// " level:" + province.getString("level")
// );
//在这里新增省份 到表中
GaoDeDistrict provinceGaoDeDistrict = new GaoDeDistrict();
provinceGaoDeDistrict.setAdCode(province.getString("adcode"));
provinceGaoDeDistrict.setName(province.getString("name"));
provinceGaoDeDistrict.setLevel(province.getString("level"));
provinceGaoDeDistrict.setParentCode("100000");
provinceGaoDeDistrict.setParentName("中华人民共和国");
provinceGaoDeDistrict.setFullName("中国" + "-" + province.getString("name"));
provinceGaoDeDistrict.setLongitude(provinceCenterSplit[0]);
provinceGaoDeDistrict.setLatitude(provinceCenterSplit[1]);
provinceGaoDeDistrict.setGmtCreate(new Date());
this.baseService.save(provinceGaoDeDistrict);
//市
JSONArray citys = province.getJSONArray("districts");
//Map<String, Object> cityMap = new HashMap<String, Object>();
for (int k = 0; k < citys.size(); k++) {
JSONObject city = citys.getJSONObject(k);
String citysCenter = city.getString("center");
String[] citysCenterSplit = citysCenter.split(",");
// System.out.println(
// "city :::::: ==== name:" + city.getString("name") +
// " center:" + city.getString("center") +
// " longitude:" + citysCenterSplit[0] + " latitude:" + citysCenterSplit[1] +
// " adcode:" + city.getString("adcode") +
// " level:" + city.getString("level") +
// " citycode:" + city.getString("citycode")
// );
// System.out.println(province.getString("name") + "-" + city.getString("name"));
//在这里新增市 到表中
GaoDeDistrict cityGaoDeDistrict = new GaoDeDistrict();
cityGaoDeDistrict.setAdCode(city.getString("adcode"));
cityGaoDeDistrict.setName(city.getString("name"));
cityGaoDeDistrict.setLevel(city.getString("level"));
cityGaoDeDistrict.setCityCode(city.getString("citycode"));
cityGaoDeDistrict.setParentCode(province.getString("adcode"));
cityGaoDeDistrict.setParentName(province.getString("name"));
cityGaoDeDistrict.setFullName(province.getString("name") + "-" + city.getString("name"));
cityGaoDeDistrict.setLongitude(citysCenterSplit[0]);
cityGaoDeDistrict.setLatitude(citysCenterSplit[1]);
cityGaoDeDistrict.setGmtCreate(new Date());
this.baseService.save(cityGaoDeDistrict);
//区
JSONArray areas = city.getJSONArray("districts");
Map<String, Object> countyMap = new HashMap<String, Object>();
for (int l = 0; l < areas.size(); l++) {
JSONObject area = areas.getJSONObject(l);
countyMap.put(area.getString("name"), area.getString("name"));
String areaCenter = area.getString("center");
String[] areaCenterSplit = areaCenter.split(",");
count++;
//list.add(province.getString("name") + "-" + city.getString("name") + "-" + area.getString("name"));
// System.out.println(province.getString("name") + "-" + city.getString("name") + "-" + area.getString("name"));
// System.out.println(
// "area :::::: ==== name:" + area.getString("name") +
// " center:" + area.getString("center") +
// " longitude:" + areaCenterSplit[0] + " latitude:" + areaCenterSplit[1] +
// " adcode:" + area.getString("adcode") +
// " level:" + area.getString("level") +
// " citycode:" + area.getString("citycode")
// );
//在这里新增区或县 到表中
GaoDeDistrict areaGaoDeDistrict = new GaoDeDistrict();
areaGaoDeDistrict.setAdCode(area.getString("adcode"));
areaGaoDeDistrict.setName(area.getString("name"));
areaGaoDeDistrict.setLevel(area.getString("level"));
areaGaoDeDistrict.setCityCode(area.getString("citycode"));
areaGaoDeDistrict.setParentCode(city.getString("adcode"));
areaGaoDeDistrict.setParentName(city.getString("name"));
areaGaoDeDistrict.setFullName(province.getString("name") + "-" + city.getString("name") + "-" + area.getString("name"));
areaGaoDeDistrict.setLongitude(areaCenterSplit[0]);
areaGaoDeDistrict.setLatitude(areaCenterSplit[1]);
areaGaoDeDistrict.setGmtCreate(new Date());
this.baseService.save(areaGaoDeDistrict);
}
// cityMap.put(city.getString("name"), countyMap);
}
//provinceMap.put(province.getString("name"), cityMap);
}
}
//查看所有省市县信息
// System.out.println(list);
return success("成功!!");
} else {
return (json.get("info"));
}
}
//获取
@PostMapping("/getAllGaoDeDistrict")
public Object getAllGaoDeDistrict(@RequestBody Map<String, Object> params) {
if (params==null){
return error("参数错误!!");
}
String adcode = (String) params.get("adcode");
// System.out.println(adcode);
JSONObject jsonObject = new JSONObject();
if (StringUtils.isBlank((String) params.get("adcode"))) {
List<GaoDeDistrict> list = this.baseService.list();
for (GaoDeDistrict gaoDeDistrict : list) {
//拼接center
String center = gaoDeDistrict.getLongitude() + "," + gaoDeDistrict.getLatitude();
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("adcode", gaoDeDistrict.getAdCode());
jsonObject2.put("center", center);
jsonObject.put(gaoDeDistrict.getName(), jsonObject2);
}
} else if (Integer.valueOf(adcode) == 100000) {//返回所有省的数据
QueryWrapper<GaoDeDistrict> sonWrapper = new QueryWrapper<>();
sonWrapper.eq("parent_code", adcode);
List<GaoDeDistrict> sonList = this.baseService.list(sonWrapper);
for (GaoDeDistrict gaoDeDistrict : sonList) {
//拼接center
String sonCenter = gaoDeDistrict.getLongitude() + "," + gaoDeDistrict.getLatitude();
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("adcode", gaoDeDistrict.getAdCode());
jsonObject2.put("center", sonCenter);
jsonObject.put(gaoDeDistrict.getName(), jsonObject2);
}
} else {
QueryWrapper<GaoDeDistrict> parentWrapper = new QueryWrapper<>();
parentWrapper.eq("ad_code", adcode);
GaoDeDistrict parents = this.baseService.getOne(parentWrapper);
// parents.getName();//获取名字
// parents.getAdCode();//获取区域代码
// parents.getLongitude();//获取经度
// parents.getLatitude();//获取纬度
//拼接center
String center = parents.getLongitude() + "," + parents.getLatitude();
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("adcode", parents.getAdCode());
jsonObject1.put("center", center);
//下级所有信息
QueryWrapper<GaoDeDistrict> sonWrapper = new QueryWrapper<>();
sonWrapper.eq("parent_code", adcode);
List<GaoDeDistrict> sonList = this.baseService.list(sonWrapper);
for (GaoDeDistrict gaoDeDistrict : sonList) {
//拼接center
String sonCenter = gaoDeDistrict.getLongitude() + "," + gaoDeDistrict.getLatitude();
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("adcode", gaoDeDistrict.getAdCode());
jsonObject2.put("center", sonCenter);
jsonObject.put(gaoDeDistrict.getName(), jsonObject2);
}
jsonObject.put(parents.getName(), jsonObject1);
}
return success("成功",jsonObject);
}
}
HttpClient相关工具类:
package com.king.common.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* HttpClient工具类
*/
public class HttpRequestUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private RequestConfig requestConfig;
private String encoding = "UTF-8";
private CloseableHttpClient httpClient;
public HttpRequestUtil() {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setDefaultMaxPerRoute(250);
cm.setMaxTotal(500);
httpClient = HttpClients.custom().setConnectionManager(cm).build();
Integer socketTimeout = 60 * 1000;
Integer connectTimeout = 60 * 1000;
Integer connectionRequestTimeout = 60 * 1000;
requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.build();
}
/**
* @param url 请求url
* @param postData POST请求时form表单封装的数据 没有时传null
* @return response返回的文本数据
* @throws Exception
*/
public String doPostRequest(String url, Map<String, Object> postData) throws Exception {
return doPostRequest(url, postData, null);
}
/**
* @param url 请求url
* @param postData POST文件上传请求时form表单封装的数据 没有时传null
* @param header 头信息,没有时传null
* @return response返回的文本数据
* @throws IOException
*/
@SuppressWarnings("rawtypes")
public String doFileUploadPostRequest(String url, Map<String, Object> postData, Map<String, Object> header) throws Exception {
CloseableHttpResponse response = null;
String result = "";
try {
if (null == postData) {
postData = new HashMap<String, Object>();
}
// 如果postData为null
if (postData == null || postData.size() <= 0) return result;
//post参数传递
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (Map.Entry<String, Object> entry : postData.entrySet()) {
if (null != entry.getValue() && !"".equals(entry.getValue())) {
if ("fileName".equals(entry.getKey())) {
File file = (File) entry.getValue();
builder.addBinaryBody(entry.getKey().toString().trim(), file,
ContentType.DEFAULT_BINARY, file.getName());
} else {
builder.addTextBody(entry.getKey().toString().trim(), entry.getValue().toString(),
ContentType.DEFAULT_BINARY);
}
}
}
// 目标地址
HttpPost httpPost = new HttpPost(url);
//头信息
if (null != header) {
for (Map.Entry<String, Object> entry : header.entrySet()) {
if (null != entry.getValue()) {
httpPost.setHeader(entry.getKey(), entry.getValue().toString());
}
}
}
httpPost.setConfig(requestConfig);
httpPost.setEntity(builder.build()); // 设置参数给Post
// 得到返回的response.
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
result = getResult(entity);
} catch (Exception e) {
e.printStackTrace();
if (null != httpClient) {
httpClient.close();
}
} finally {
if (response != null) {
EntityUtils.consume(response.getEntity()); //会自动释放连接
response.close();
}
}
return result;
}
/**
* @param url 请求url
* @param postData POST请求时form表单封装的数据 没有时传null
* @param header 头信息,没有时传null
* @return response返回的文本数据
* @throws IOException
*/
@SuppressWarnings("rawtypes")
public String doPostRequest(String url, Map<String, Object> postData, Map<String, Object> header) throws Exception {
CloseableHttpResponse response = null;
String result = "";
try {
if (null == postData) {
postData = new HashMap<String, Object>();
}
//post参数传递
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : postData.entrySet()) {
if (null != entry.getValue()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
}
// 目标地址
HttpPost httpPost = new HttpPost(url);
//头信息
if (null != header) {
for (Map.Entry<String, Object> entry : header.entrySet()) {
if (null != entry.getValue()) {
httpPost.setHeader(entry.getKey(), entry.getValue().toString());
}
}
}
httpPost.setConfig(requestConfig);
httpPost.setEntity(new UrlEncodedFormEntity(params, encoding)); // 设置参数给Post
// 得到返回的response.
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
result = getResult(entity);
} catch (Exception e) {
logger.error(e.getMessage(), e);
if (null != httpClient) {
httpClient.close();
}
} finally {
if (response != null) {
EntityUtils.consume(response.getEntity()); //会自动释放连接
response.close();
}
}
return result;
}
/**
* @param url 请求url
* @return response返回的文本数据
* @throws Exception
*/
public String doGetRequest(String url) throws Exception {
return doGetRequest(url, null);
}
/**
* @param url 请求url
* @param header 头信息,没有时传null
* @return response返回的文本数据
* @throws Exception
*/
public String doGetRequest(String url, Map<String, Object> header) throws Exception {
CloseableHttpResponse response = null;
String result = "";
try {
HttpGet httpGet = new HttpGet(url);
//头信息
if (null != header) {
for (Map.Entry<String, Object> entry : header.entrySet()) {
if (null != entry.getValue()) {
httpGet.setHeader(entry.getKey(), entry.getValue().toString());
}
}
}
httpGet.setConfig(requestConfig);
// 得到返回的response.
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
result = getResult(entity);
} catch (Exception e) {
if (null != httpClient) {
httpClient.close();
}
} finally {
if (response != null) {
EntityUtils.consume(response.getEntity()); //会自动释放连接
response.close();
}
}
return result;
}
/**
* @param url 请求url
* @param header 头信息,没有时传null
* @return response返回的文本数据
* @throws IOException
*/
@SuppressWarnings("rawtypes")
public String doPostRequest(String url, String xmlStr, Map<String, Object> header) throws Exception {
CloseableHttpResponse response = null;
String result = "";
try {
// 目标地址
HttpPost httpPost = new HttpPost(url);
//头信息
if (null != header) {
for (Map.Entry<String, Object> entry : header.entrySet()) {
if (null != entry.getValue()) {
httpPost.setHeader(entry.getKey(), entry.getValue().toString());
}
}
}
StringEntity myEntity = new StringEntity(xmlStr, encoding);
httpPost.setConfig(requestConfig);
httpPost.setEntity(myEntity); // 设置参数给Post
if (null != header && !header.containsKey("content-type")) {
httpPost.addHeader("content-type", "text/xml;charset=utf-8");
}
// 得到返回的response.
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
result = getResult(entity);
} catch (Exception e) {
if (null != httpClient) {
httpClient.close();
}
} finally {
if (response != null) {
EntityUtils.consume(response.getEntity()); //会自动释放连接
response.close();
}
}
return result;
}
/**
* @param url 请求url
* @return response返回的文本数据
* @throws Exception
*/
public HttpEntity doGetEntity(String url) throws Exception {
return doGetEntity(url, null);
}
/**
* @param url 请求url
* @param header 头信息,没有时传null
* @return response返回的文本数据
* @throws Exception
*/
public HttpEntity doGetEntity(String url, Map header) throws Exception {
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
// 得到返回的response.
HttpResponse response = httpClient.execute(httpGet);
return response.getEntity();
}
/**
* 返回结果转String
*
* @param entity HttpEntity
* @return String
*/
private String getResult(HttpEntity entity) {
StringBuilder sbResult = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
entity.getContent(), encoding));
String line;
while ((line = reader.readLine()) != null) {
sbResult.append(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return sbResult.toString();
}
/**
* 获取远程的图片到指定路劲
*
* @param url 请求url
* @param fullFileName 文件全路径名称
* @return bo
*/
/* public boolean downloadRemoteImg(String url, String fullFileName) {
boolean bo = false;
InputStream is = null;
FileOutputStream output = null;
try {
is = doGetEntity(url).getContent();
File file = new File(fullFileName);
output = FileUtils.openOutputStream(file);
IOUtils.copy(is, output);
bo = true;
} catch (Exception e) {
bo = false;
} finally {
if (null != output) {
IOUtils.closeQuietly(output);
}
if (null != is) {
IOUtils.closeQuietly(is);
}
}
return bo;
}*/
/*
*
* */
public String getTransactionDataHttpPost(Map<String, Object> params) {
// //分页信息
String page_info = (String) params.get("page_info");
//查询条件
String where_info = (String) params.get("where_info");
// 获取连接客户端工具 创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
String entityStr = null;
CloseableHttpResponse response = null;
try {
// 创建POST请求对象
HttpPost httpPost = new HttpPost("http://www.idecard.cn/ECardWeb/ApiSign/queryConsDetail");
// 创建请求参数
JSONObject parm = new JSONObject(new LinkedHashMap<>());
parm.put("page_info", page_info);
parm.put("where_info", where_info);
//parm.put("page_info","{\"rows\":1,\"page\":1,\"sidx\":\"F_AccDateTime\",\"sord\":\"DESC\",\"records\":0,\"total\":0}");
//parm.put("where_info","{\"start_time\":\"2021-10-01 00:00:00\",\"end_time\":\"2021-12-31 00:00:00\"}");
String companyId = "1000168853";
String nonce = "123456";
//签名密钥
String signatureKey = "CA3CDCC4185CECC3D6C63370DE880D57";
//装填参数
StringEntity s = new StringEntity(parm.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
//设置参数到请求对象中
httpPost.setEntity(s);
// 浏览器表示
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
// {"companyId":"1000168853","timespan":"20211229090259","nonce":"123456","signature":"e2d1b605b3059b401e7f9a75d4c8ea24"}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String timespan = sdf.format(new Date());
String s1 = parm.toString();
/**companyId + timespan + nonce + 报文主体(按字母顺序排序) + 签名密钥
* ,进行MD5 运 算,取小写字符串得到签名串
*/
String sign = companyId + timespan + nonce + s1 + signatureKey;
String md5Str = ThirtyTwoMD5.getMD5Str(sign);
String body_sign = "{\"companyId\":\"" + "1000168853" + "\",\"timespan\":\"" + timespan + "\",\"nonce\":\"" + "123456" + "\",\"signature\":\"" + md5Str + "\"}";
//添加请求头
httpPost.addHeader("body_sign", body_sign);
// 传输的类型
httpPost.addHeader("Content-Type", "application/json");
// 执行请求 返回响应实体
response = httpClient.execute(httpPost);
// 获得响应的消息
HttpEntity entity = response.getEntity();
// 使用Apache提供的工具类进行转换成字符串
entityStr = EntityUtils.toString(entity, "UTF-8");
System.out.println("HTTP头部信息:" + Arrays.toString(response.getAllHeaders()));
} catch (ClientProtocolException e) {
System.err.println("Http协议出现问题");
e.printStackTrace();
} catch (ParseException e) {
System.err.println("解析错误");
e.printStackTrace();
} catch (IOException e) {
System.err.println("IO异常");
e.printStackTrace();
} finally {
// 释放连接
if (null != response) {
try {
response.close();
httpClient.close();
} catch (IOException e) {
System.err.println("释放连接出错");
e.printStackTrace();
}
}
}
// 打印响应内容
return entityStr;
}
}