httpClient远程调技术的使用,使用httpClient调用远程接口获取数据,再将获取到的数据信息通过远程接口推送给第三方

最近做项目需要通过第三方公司提供的接口进行数据抽取,保存到数据库,再将抽取过来的数据根据业务需求再查询出来推送给其他公司做数据处理。所有就使用到了httpClient远程调技术。现在将其整理出来供参考。
先是数据抽取 使用httpClient doGet请求获取数据:

/**
	 * 定时任务获取第三方业务数据 预计1天一次
	 */
	@Override
	@Transactional
	public void getHyZfyw() {
		System.out.println("========zfyw start========");
		try {
			List<Map<String, Object>> jyList = getOrgList(false);
			if (jyList != null && jyList.size() > 0) {
			    //同步业务数据方法
				zfywTbService.synchroZfyw(jyList);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		System.out.println("========zfyw end========");
	}

/**
	 * 同步业务数据方法  业务层接口
	 * @param jyList 监狱列表
	 */
	void synchroZfyw(List<Map<String, Object>> jyList);
	//业务层实现类
	@Override
	public void synchroZfyw(List<Map<String, Object>> jyList) {
		//String time = Util.toStr(new Date(), Util.DF_DATE);
		//同步昨天数据
		String time = Util.getYesterdayDate(false);
		String cjpc = Synchro.getUUID();
		Tblog tblog = new Tblog(null, null, Synchro.Opt.START, null, new Date(), cjpc);
		tblogService.save(tblog);
		try {
		    //调用接口方法
			zfShgx(time, cjpc, jyList);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		tblog = new Tblog(null, null, Synchro.Opt.END, null, new Date(), cjpc);
		tblogService.save(tblog);
	}
//调用接口方法
void zfShgx(String time, String cjpc, List<Map<String, Object>> jyList);
//接口方法实现
@Override
    public void zfShgx(String time, String cjpc, List<Map<String, Object>> jyList) {
    	Tblog tblog = null;
    	String corp = null;
    	String opt = null;
    	zfShgxService.backups();
    	tblog = new Tblog(Synchro.Zfyw.ENTITY_ZF_SHGX, null, Synchro.Opt.BACKUPS, null, new Date(), cjpc);
    	tblogService.save(tblog);
    	for (Map<String, Object> map : jyList) {
			corp = (String)map.get("corps");
			try {
			    //调用同步的接口方法
				zfShgxService.synchroZfShgx(corp, time, cjpc);
				opt = Synchro.Opt.INSERT;
			} catch (Exception e) {
				e.printStackTrace();
				opt = Synchro.Opt.ERROR;
			}
			tblog = new Tblog(Synchro.Zfyw.ENTITY_ZF_SHGX, (String)map.get("jyCode"), opt, null, new Date(), cjpc);
			tblogService.save(tblog);
		}
    	tblog = new Tblog(Synchro.Zfyw.ENTITY_ZF_SHGX, null, Synchro.Opt.COMPLETE, null, new Date(), cjpc);
		tblogService.save(tblog);
    }
//同步数据的接口方法
public void synchroZfShgx(String corp, String time, String cjpc);
//同步数据的接口方法实现
@Override
	public void synchroZfShgx(String corp, String time, String cjpc) {
	    //httpClient 工具类方法调用  获取远程数据
		List<Map<String, Object>> data = ZfywHttpClientUtil.getData(Synchro.Zfyw.ENTITY_ZF_SHGX, corp, time);
		Map<String, Object> zfjbxx = null;
		List<Map<String, Object>> zfshgxList = null;
		ZfShgx zfshgx = null;
		List<ZfShgx> list = null;
		if (data != null) {
			list = new ArrayList<ZfShgx>();
			Date cjrq = new Date();
			Date urlTime = Util.toDate(time, Util.DF_DATE);
			for (Map<String, Object> temp : data) {
				zfjbxx = (Map<String, Object>)temp.get(Synchro.Member.DEFAULT_ZFJBXX);
				zfshgxList = (List<Map<String, Object>>)zfjbxx.get(Synchro.Member.DEFAULT_ZFSHGX);
				if (zfshgxList != null && zfshgxList.size() > 0) {
					for (Map<String, Object> map : zfshgxList) {
						zfshgx = new ZfShgx();
						this.convert(zfshgx, map, zfjbxx, corp, urlTime, cjpc, cjrq);
						list.add(zfshgx);
					}
				}
			}
			this.batchInsert(list);
		}
	}
//HttpClientUtil工具类
public class ZfywHttpClientUtil {

	public static List<Map<String, Object>> getData(String type, String corp, String time) {
		List<Map<String, Object>> dataList = null;
		//httpClientUilt 工具类 封装了doGet方法
		String _root = HttpClientUtil.doGet(Synchro.HOST_ZFYW + type + "?corp=" + corp + "&time=" + time);
		if (_root != null) {
			JSONObject jsonObject = JSONObject.parseObject(_root);
		    Map<String, Object> root = (Map<String, Object>)jsonObject;
		    if (root != null) {
		    	String code = (String)root.get("code");
			    if (Synchro.RETURN_CODE_SUCCESS.equals(code)) {
			    	int count = (Integer)root.get("count");
			    	if (count > 0) {
			    		Map<String, Object> data = (Map<String, Object>)root.get("data");
			    		if (data != null) {
			    			dataList = (List<Map<String, Object>>)data.get("data");
			    		}
			    	}
			    }
		    }
		}
	    return dataList;
	}
	
	public static Map<String, Object> getDzwp(String type, String secCode, String period) {
		Map<String, Object> data = null;
		String requestUrl = Synchro.HOST_DZWP  + "?type=" + type + "&secCode=" + secCode;
		if (period != null) {
			requestUrl = requestUrl + "&period=" + period;
		}
		String _root = HttpClientUtil.doGet(requestUrl);
		if (_root != null) {
			JSONArray jsonArray = JSONArray.parseArray(_root);
			List list = (List)jsonArray;
			if (list != null && list.size() > 0) {
				data = (Map<String, Object>)list.get(0);
			}
		}
	    return data;
	}
	
	public static void main(String[] args) throws Exception {
		//photo();
		getDzwp(null, null, null);
	}
	
	public static void synchroJyList() {
		String corpsUrl = "http://???:6789?/corps/";
		System.out.println(HttpClientUtil.doGet(corpsUrl));
	}
	
	
	public static void synchro() {
		System.out.println("========start=======");
		List<String> corps = new ArrayList<String>();
		corps.add("73878031185de329fa6876725c100000");
		corps.add("73878031185de329fa6876725c100001");
		corps.add("73878031185de329fa6876725c100002");
		corps.add("73878031185de329fa6876725c100003");
		corps.add("73878031185de329fa6876725c100004");
		corps.add("73878031185de329fa6876725c100006");
		corps.add("73878031185de329fa6876725c100005");
		corps.add("73878031185de329fa6876725c100007");
		corps.add("73878031185de329fa6876725c100104");
		corps.add("73878031185de329fa6876725c100101");
		corps.add("73878031185de329fa6876725c100105");
		corps.add("73878031185de329fa6876725c100103");
		corps.add("73878031185de329fa6876725c100107");
		List<Map<String, Object>> list = null;
		for (String corp : corps) {
			list = getData("entity_zf_ttbh_sj", corp, "2019-04-24");
			System.out.println("============>" + list);
		}
		System.out.println("========end=======");
	}
	
	public static void photo() throws Exception {
		HttpEntity httpEntity = httpGet("???/displayZfzp/6EE87FE8275CE42F8CA014D958B6108F");
		InputStream inputStream = httpEntity.getContent();
		FileUtils.copyToFile(inputStream, new File("???/6EE87FE8275CE42F8CA014D958B6108F.jpg"));
		inputStream.close();
	}
	
	public static HttpEntity httpGet(String requestUrl) {
		HttpEntity httpEntity = null;
		try {
			// 创建httpClient
			HttpClient httpClient = HttpClients.createDefault();
			
			// 声明并初始化request
			HttpGet request = new HttpGet(requestUrl);
			
			//设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
            request.setConfig(requestConfig);
            
            // 执行Http请求
            HttpResponse httpResponse = httpClient.execute(request);
			
			if (httpResponse != null) {
				httpEntity = httpResponse.getEntity();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return httpEntity;
	}
	
}
public class HttpClientUtil {  

  public static String doGet(String url, Map<String, String> param) {  

      // 创建Httpclient对象  
      CloseableHttpClient httpclient = HttpClients.createDefault();  

      String resultString = "";  
      CloseableHttpResponse response = null;  
      try {  
          // 创建uri  
          URIBuilder builder = new URIBuilder(url);  
          if (param != null) {  
              for (String key : param.keySet()) {  
                  builder.addParameter(key, param.get(key));  
              }  
          }  
          URI uri = builder.build();  

          // 创建http GET请求  
          HttpGet httpGet = new HttpGet(uri);  
          httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");
          httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
          httpGet.setHeader("Accept-Encoding", "gzip,deflate,sdch");	//需要加上这个头字段
          httpGet.addHeader("Content-type","application/json; charset=utf-8");
          // 执行请求  
          response = httpclient.execute(httpGet);  
          // 判断返回状态是否为200  
          if (response.getStatusLine().getStatusCode() == 200) {  
        	  InputStream in = null;
				HttpEntity entity = response.getEntity();
				Header header = entity.getContentEncoding();
				if(header != null && header.getValue().equalsIgnoreCase("gzip")){	//判断返回内容是否为gzip压缩格式
					GzipDecompressingEntity gzipEntity = new GzipDecompressingEntity(entity);
					in = gzipEntity.getContent();
				}else{
					in = entity.getContent();
				}
				resultString = getHTMLContent(in);
          }  
      } catch (Exception e) {  
          e.printStackTrace();  
      } finally {  
          try {  
              if (response != null) {  
                  response.close();  
              }  
              httpclient.close();  
          } catch (IOException e) {  
              e.printStackTrace();  
          }  
      }  
      return resultString;  
  }  

  public static String doGet(String url) {  
      return doGet(url, null);  
  }  

	private static String getHTMLContent(InputStream in) {
		StringBuffer sb = new StringBuffer();
		BufferedReader br = null;
		try {
		 br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
	
			String line = null;
			while((line=br.readLine())!=null){
				sb.append(line);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return sb.toString();
	}
  public static String doPost(String url, Map<String, String> param) {  
      // 创建Httpclient对象  
      CloseableHttpClient httpClient = HttpClients.createDefault();  
      CloseableHttpResponse response = null;  
      String resultString = "";  
      try {  
          // 创建Http Post请求  
          HttpPost httpPost = new HttpPost(url);  
          // 创建参数列表  
          if (param != null) {  
              List<NameValuePair> paramList = new ArrayList<>();  
              for (String key : param.keySet()) {  
                  paramList.add(new BasicNameValuePair(key, param.get(key)));  
              }  
              // 模拟表单  
              UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);  
              httpPost.setEntity(entity);  
          }  
          // 执行http请求  
          response = httpClient.execute(httpPost);  
          resultString = EntityUtils.toString(response.getEntity(), "utf-8");  
      } catch (Exception e) {  
          e.printStackTrace();  
      } finally {  
          try {  
              response.close();  
          } catch (IOException e) {  
              // TODO Auto-generated catch block  
              e.printStackTrace();  
          }  
      }  

      return resultString;  
  }  

  public static String doPost(String url) {  
      return doPost(url, null);  
  }  
    
  public static String doPostJson(String url, String json) {  
      // 创建Httpclient对象  
      CloseableHttpClient httpClient = HttpClients.createDefault();  
      CloseableHttpResponse response = null;  
      String resultString = "";  
      try {  
          // 创建Http Post请求  
          HttpPost httpPost = new HttpPost(url);  
          // 创建请求内容  
          StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);  
          httpPost.setEntity(entity);  
          // 执行http请求  
          response = httpClient.execute(httpPost);  
          resultString = EntityUtils.toString(response.getEntity(), "utf-8");  
      } catch (Exception e) {  
          e.printStackTrace();  
      } finally {  
          try {  
              response.close();  
          } catch (IOException e) {  
              // TODO Auto-generated catch block  
              e.printStackTrace();  
          }  
      }  
      return resultString;  
  }  
}

使用HTTPClient 的dopost请求获取数据:

/**
	 * 定时任务获取华宇数据 预计1天一次
	 */
	@Override
	@Transactional
	public void getHY() {
		try{

			zfStatService.deleteCurrentDay();

			//统计数据
			List<Map<String ,Object>>  listJyCorsp = getOrgList(true);
			//**能力
			zfStatZyService.synchroZfStatZyJyGynl(listJyCorsp);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
   public void synchroZfStatZyJyGynl(List<Map<String ,Object>> list) throws BusinessLayerException;
   @Override
	public void synchroZfStatZyJyGynl(List<Map<String ,Object>> list) throws BusinessLayerException {
		
		Date startDate = Util.toDate(Util.getCurrentDate(), Util.DF_DATE);
		
		String type = "STAT_ZF_GYNL";
		
		try {
			
			List<ZfStatZyDto> dtoList = ZfStatZyHttpClient.entityZfStatZyJyGynl();
			
			if(dtoList != null && dtoList.size()>0) {
				
				System.out.println("10.开始同步" + Util.toStr(startDate, Util.DF_DATE) + "【**】统计信息" + dtoList.size() + "条");
				logger.info("10.开始同步" + Util.toStr(startDate, Util.DF_DATE) + "【**能力】统计信息" + dtoList.size() + "条");
				
				this.synchoZfStats(dtoList,type,list);
			}
		} catch (Exception e) {
			throw new BusinessLayerException("10.同步【**能力】统计发生异常, Exception info is " + e);
		}
	}
/**
 * Description: 暂押罪犯统计信息调用HttpClient工具类
 * @author zhou.jian
 *
 * @Date 2019年2月21日
 */
public class ZfStatZyHttpClient {

	/**
	 * 罪犯信息接口地址
	 */
	private static String host = PropertiesUtil.getValueByKeyUnchanged("application", "synchro.zfxx.url"); //"http://192.168.8.90:80/jy-query/api/v1"
    /**
     * 日志工具
     */
    private static final Logger logger = LoggerFactory.getLogger(ZfStatZyHttpClient.class);
	/**
	 * Gson工具
	 */
	private final static Gson gson = new GsonBuilder().create();
	
	private static ZfStatZyHttpClient currentWSHttpClient = new ZfStatZyHttpClient();
	
	private ZfStatZyHttpClient() {
		
	}
	
	private ZfStatZyHttpClient(String host) {
		ZfStatZyHttpClient.host = host;
	}
	
	public static synchronized ZfStatZyHttpClient getWSHttpClient(String host) {
		ZfStatZyHttpClient.host = host;
		return currentWSHttpClient;
	}
	
	public static synchronized ZfStatZyHttpClient getWSHttpClient() {
		if(currentWSHttpClient != null) {
			return currentWSHttpClient;
		}
		return new ZfStatZyHttpClient();
	}
	
	public static String getHost() {
		return host;
	}

	public static void setHost(String host) {
		ZfStatZyHttpClient.host = host;
	}
	
	public String httpUpdate(String requestUrl, String parameters) {
		String data = "";
		HttpClient client = HttpClients.createDefault();
		HttpPut httpPut = new HttpPut(host + requestUrl);
		httpPut.addHeader("content-type", "application/json");
		httpPut.addHeader("Accept", "application/json");
		System.out.println("executing request " + httpPut.getURI());
		try {
			httpPut.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
			HttpResponse response = client.execute(httpPut);
			System.out.println("statusCode:" + response.getStatusLine().getStatusCode());
			Header[] headers = response.getAllHeaders();
			for (int i = 0; i < headers.length; i++)
				System.out.println(headers[i].getName() + ":" + headers[i].getValue());
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					System.out.println("--------------------------------------");
					data = EntityUtils.toString(entity, "UTF-8");
					System.out.println("Response content: " + data);
					System.out.println("--------------------------------------");
				}
			} finally {
				System.out.println();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}
	
	public String httpUpdate(String requestUrl) {
		String data = "";
		HttpClient client = HttpClients.createDefault();
		HttpPut httpPut = new HttpPut(host + requestUrl);
		httpPut.addHeader("content-type", "application/json");
		httpPut.addHeader("Accept", "application/json");
		System.out.println("executing request " + httpPut.getURI());
		try {
			HttpResponse response = client.execute(httpPut);
			System.out.println("statusCode:" + response.getStatusLine().getStatusCode());
			Header[] headers = response.getAllHeaders();
			for (int i = 0; i < headers.length; i++)
				System.out.println(headers[i].getName() + ":" + headers[i].getValue());
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					System.out.println("--------------------------------------");
					data = EntityUtils.toString(entity, "UTF-8");
					System.out.println("Response content: " + data);
					System.out.println("--------------------------------------");
				}
			} finally {
				System.out.println();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}
	
	public Integer httpDelete(String requestUrl) {
		Integer data = Integer.valueOf(0);
		HttpClient client = HttpClients.createDefault();
		HttpDelete delete = new HttpDelete(host + requestUrl);
		delete.addHeader("content-type", "application/json");
		delete.addHeader("Accept", "application/json");
		System.out.println("executing request " + delete.getURI());
		try {
			HttpResponse response = client.execute(delete);
			System.out.println("statusCode:" + response.getStatusLine().getStatusCode());
			Header[] headers = response.getAllHeaders();
			for (int i = 0; i < headers.length; i++)
				System.out.println(headers[i].getName() + ":" + headers[i].getValue());
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					System.out.println("--------------------------------------");
					String text = EntityUtils.toString(entity, "UTF-8");
					System.out.println("Response content: " + text);
					System.out.println("--------------------------------------");
					if (StringUtils.isNotBlank(text))
						data = Integer.valueOf(text);
				}
			} finally {
				System.out.println();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}

	public String postForm(String requestUrl, String parameters) {
		String result = "";

		HttpClient client = HttpClients.createDefault();

		HttpPost httppost = new HttpPost(host + requestUrl);

		httppost.addHeader("content-type", "application/json");
		httppost.addHeader("Accept", "application/json");
		try {
			httppost.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
			System.out.println("executing request " + httppost.getURI());
			HttpResponse response = client.execute(httppost);
			System.out.println("statusCode:" + response.getStatusLine().getStatusCode());
			Header[] headers = response.getAllHeaders();
			for (int i = 0; i < headers.length; i++)
				System.out.println(headers[i].getName() + ":" + headers[i].getValue());
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					result = EntityUtils.toString(entity, "UTF-8");
					System.out.println("--------------------------------------" + result);
					System.out.println("--------------------------------------");
					System.out.println("--------------------------------------");
				}
			} finally {
				System.out.println();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			System.out.println();
		}
		return result;
	}

	public String postForm(String requestUrl) {
		String result = "";

		HttpClient client = HttpClients.createDefault();

		HttpGet request = new HttpGet(host + requestUrl);
		request.addHeader("content-type", "application/json");
		request.addHeader("Accept", "application/json");
		try {
			System.out.println("executing request " + request.getURI());
			HttpResponse response = client.execute(request);
			System.out.println("statusCode:" + response.getStatusLine().getStatusCode());
			Header[] headers = response.getAllHeaders();
			for (int i = 0; i < headers.length; i++)
				System.out.println(headers[i].getName() + ":" + headers[i].getValue());
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					result = EntityUtils.toString(entity, "UTF-8");
					System.out.println("--------------------------------------" + result);
					System.out.println("--------------------------------------");
					System.out.println("--------------------------------------");
				}
			} finally {
				System.out.println();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			System.out.println();
		}
		return result;
	}

	/**
	 * get请求
	 * @param requestUrl
	 * @return
	 */
	public static HttpEntity httpGet(String requestUrl) {
		HttpEntity httpEntity = null;
		try {
			// 创建httpClient
			HttpClient httpClient = HttpClients.createDefault();
			
			// 声明并初始化request
			HttpGet request = new HttpGet(host + requestUrl);
			request.addHeader("content-type", "application/json");
			request.addHeader("Accept", "application/json");
			// System.out.println("executing request " + request.getURI());
			
			//设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
            request.setConfig(requestConfig);
            
            // 执行Http请求
            HttpResponse httpResponse = httpClient.execute(request);
			
			if(httpResponse != null) {
				httpEntity = httpResponse.getEntity();
			}
		} catch (ClientProtocolException e) {
			logger.error("Get请求" + host + requestUrl + "发生异常, Exception info is " + e);
		} catch (IOException e) {
			logger.error("Get请求" + host + requestUrl + "发生异常, Exception info is " + e);
		}
		return httpEntity;
	}

	/**
	 * post请求
	 * @param requestUrl
	 * @return
	 */
	public static HttpEntity httpPost(String requestUrl) {
		HttpEntity httpEntity = null;
		try {
			// 创建httpClient
			HttpClient httpClient = HttpClients.createDefault();
			
			// 声明并初始化request
			HttpPost request = new HttpPost(host + requestUrl);
			request.addHeader("content-type", "application/json");
			request.addHeader("Accept", "application/json");
			// System.out.println("executing request " + request.getURI());
			
			//设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
            request.setConfig(requestConfig);
            
            // 执行Http请求
            HttpResponse httpResponse = httpClient.execute(request);
			
			if(httpResponse != null) {
				httpEntity = httpResponse.getEntity();
			}
		} catch (ClientProtocolException e) {
			logger.error("Post请求" + host + requestUrl + "发生异常, Exception info is " + e);
		} catch (IOException e) {
			logger.error("Post请求" + host + requestUrl + "发生异常, Exception info is " + e);
		}
		return httpEntity;
	}
	
	/**
	 * post请求
	 * @param requestUrl
	 * @return
	 */
	public static HttpEntity httpPost(String requestUrl, JsonObject jsonObject) {
		HttpEntity httpEntity = null;
		try {
			// 创建httpClient
			HttpClient httpClient = HttpClients.createDefault();
			
			// 声明并初始化request
			HttpPost request = new HttpPost(host + requestUrl);
			request.addHeader("content-type", "application/json");
			request.addHeader("Accept", "application/json");
			// System.out.println("executing request " + request.getURI());
			
			// 请求体
            StringEntity entity = new StringEntity(gson.toJson(jsonObject),"utf-8");//解决中文乱码问题
            entity.setContentEncoding("UTF-8");    
            entity.setContentType("application/json");    
            request.setEntity(entity); 
			
			//设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
            request.setConfig(requestConfig);
            
            // 执行Http请求
            HttpResponse httpResponse = httpClient.execute(request);
			
			if(httpResponse != null) {
				httpEntity = httpResponse.getEntity();
			}
		} catch (ClientProtocolException e) {
			logger.error("请求" + host + requestUrl + "发生异常, Exception info is " + e);
		} catch (IOException e) {
			logger.error("请求" + host + requestUrl + "发生异常, Exception info is " + e);
		}
		return httpEntity;
	}
	
public static List<ZfStatZyDto> entityZfStatZyJyGynl() throws RESTHttpClientException {
		
		List<ZfStatZyDto> dtoList = null;
		
		try {
			dtoList = statJyGynl("stat_zf_gynl","00000000000000000000000000000000");
		} catch (Exception e) {
			throw new RESTHttpClientException("10.调用ZfStatZyHttpClient,获取【**能力】统计信息发生异常, Exception info is " + e);
		}
		return dtoList;
	}
	
}

下面是数据推送:

/**
	 * 每分钟推送数字冰雹
	 */
	@Transactional
	public void tsSzbb() {
		System.out.println("========>开始推送数字冰雹");
		String cjpc = Synchro.getUUID();
		Tblog tblog = new Tblog(Synchro.Zfyw.SZBB, null, Synchro.Opt.START, null, new Date(), cjpc);
		tblogService.save(tblog);

		List<String> jyList = SzbbUtil.initSzbb();
		for (String jyCode : jyList) {
			System.out.println("==========>" + jyCode);
			//推送市局
			tsSjSzbb(cjpc, jyCode);
			System.out.println(jyCode + "========>推送完成");
		}
		tblog = new Tblog(Synchro.Zfyw.SZBB, null, Synchro.Opt.END, null, new Date(), cjpc);
		tblogService.save(tblog);
		System.out.println("========>结束推送数字冰雹");
	}

private void tsSjSzbb(String cjpc, String jyCode) {
		Tblog tblog = null;
		//3.1	日常管控
		//3.1.1	今日值班情况信息接口
		try {
			rcgkService.getSjJrzbList(jyCode);
		} catch (Exception e) {
			e.printStackTrace();
		tblog = new Tblog(Synchro.Zfyw.SZBB_FXPG + "#" + jyCode, null, Synchro.Opt.COMPLETE, null, new Date(), cjpc);
		tblogService.save(tblog);
	}
	public void getSjJrzbList(String jyCode);
	/**
	 * 1.今日值班信息接口
	 * @return 结果集
	 */
	@Override
	public void getSjJrzbList(String jyCode) {
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("jyCode", jyCode);
		// 1.1.值班长集合
		List<Map<String, Object>> DutyLeaderList = rcgkDao.getSjJrzbzList(param);
		// 1.2.**值班员集合
		List<Map<String, Object>> DutyStaffList = rcgkDao.getSjZbyList(param);
		// 1.3.**机关值班长集合
		List<Map<String, Object>> DutyOfficerList = rcgkDao.getSjJgzbzList(param);
		//1.4.**总值班长集合
		List<Map<String, Object>> DutyBranchLeaderList = rcgkDao.getFjJrzbzList(param);
		//1.5.**机关值班长集合
		List<Map<String, Object>> DutyBranchOfficerList =  rcgkDao.getFjJgzbzList(param);
		// 1.6.**值班人员集合
		List<Map<String, Object>> DutyOthersPrisonList = rcgkDao.getJszbryList(param);

		for(Map<String, Object> m : DutyOthersPrisonList){
			param.put("PrisonAreaName", SzbbUtil.getNameByJyCode((String)m.get("PrisonAreaName")));
		}

		//推送数据的当前时间
		String Time = Util.toStr(Util.toDate(Util.getCurrentDate(), Util.DF_TIME), Util.DF_TIME);

		Map<String,Object> map = new HashMap<String,Object>();
		map.put("DutyLeaderList", DutyLeaderList);
		map.put("DutyStaffList", DutyStaffList);
		map.put("DutyOfficerList", DutyOfficerList);
		map.put("DutyBranchLeaderList", DutyBranchLeaderList);
		map.put("DutyBranchOfficerList", DutyBranchOfficerList);
		map.put("DutyOthersPrisonList", DutyOthersPrisonList);
		map.put("Time", Time);

		Gson gson = new Gson();
		//最终数据结果转换成json格式
		JsonObject newParams = new JsonObject();
		String jsonMap = gson.toJson(map);
		newParams.addProperty("json", jsonMap);
		System.out.println(jsonMap);
		String obj = null;
		try {
			obj = SzbbHttpClient.entityJrzb(param, newParams);
			System.out.println(" 【1.1.今日值班】 --> " + obj);
		} catch (RESTHttpClientException e) {
			e.printStackTrace();
		}

	}
package com.cesgroup.prison.httpclient.zfxx;

import java.io.IOException;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cesgroup.framework.exception.RESTHttpClientException;
import com.cesgroup.framework.utils.Util;
import com.cesgroup.prison.httpclient.util.SzbbUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

/**
 * Description: 【数字冰雹】信息调用HttpClient工具类 
 * 			     --- 1.日常管控 ---
 * @author zhou.jian
 *
 * @Date 2019年2月24日
 */
public class SzbbHttpClient {

	/**
     * 日志工具
     */
    private static final Logger logger = LoggerFactory.getLogger(SzbbHttpClient.class);
	
    /**
	 * Gson工具
	 */
	private final static Gson gson = new GsonBuilder().create();
	
	private static SzbbHttpClient currentWSHttpClient = new SzbbHttpClient();
	
	private SzbbHttpClient() {
		
	}
	
	public static synchronized SzbbHttpClient getWSHttpClient() {
		if(currentWSHttpClient != null) {
			return currentWSHttpClient;
		}
		return new SzbbHttpClient();
	}
	
	/*=====================================================*/
	
	
	/**
	 * post请求
	 * @param requestUrl
	 * @return
	 */
	public static HttpEntity httpPost(Map<String,Object> param, String requestUrl, JsonObject jsonObject) {
		HttpEntity httpEntity = null;
		String host = SzbbUtil.getUrlByJyCode((String)param.get("jyCode"));
		try {
			// 1.创建httpClient
			HttpClient httpClient = HttpClients.createDefault();
			
			// 2.声明并初始化request
			HttpPost request = new HttpPost(host + requestUrl);
			request.addHeader("content-type", "application/json");
			request.addHeader("Accept", "application/json");
			// System.out.println("executing request " + request.getURI());
			
			// 3.请求体
            StringEntity entity = new StringEntity(gson.toJson(jsonObject),"utf-8");//解决中文乱码问题
            entity.setContentEncoding("UTF-8");    
            entity.setContentType("application/json");    
            request.setEntity(entity); 
			
			//4.设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
            request.setConfig(requestConfig);
            
            // 5.执行Http请求
            HttpResponse httpResponse = httpClient.execute(request);
			
			if(httpResponse != null) {
				httpEntity = httpResponse.getEntity();
			}
			
		} catch (ClientProtocolException e) {
			logger.error("请求" + host + requestUrl + "发生异常, Exception info is " + e);
		} catch (IOException e) {
			logger.error("请求" + host + requestUrl + "发生异常, Exception info is " + e);
		}
		return httpEntity;
	}
	
	
	
	/*==========================    业务数据推送     ===========================*/
	
	
	/**
	 * 1.日常管控--今日值班
     *
	 * @return
	 * @throws RESTHttpClientException
	 */
	public static String entityJrzb(Map<String,Object> param, JsonObject newParams) throws RESTHttpClientException {
		
		// Description: 请求Url拼接参数
		StringBuffer requestUrl = new StringBuffer();
		requestUrl.append("IDayDuty");
		
		String content = null;
		try {
			
			HttpEntity httpEntity = httpPost(param,requestUrl.toString(),newParams);
			
			content = httpEntity != null ? EntityUtils.toString(httpEntity) : "";
			System.out.println("推送数据返回值  ===> "+content);
			
		} catch (Exception e) {
			throw new RESTHttpClientException("调用【SzbbHttpClient】推送【1.1.日常管控--今日值班】信息发生异常, Exception info is " + e);
		}
		return content;
	}

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值