Commit 39040bc7 authored by gaozhentao's avatar gaozhentao

修改http请求方式,修改getpost 处理方式

parent 1562caf6
...@@ -20,6 +20,7 @@ public class BasicTask { ...@@ -20,6 +20,7 @@ public class BasicTask {
* @param isAlive * @param isAlive
*/ */
Boolean insertToKairos(HttpClient client, String ip, int port, long dur, boolean isAlive) { Boolean insertToKairos(HttpClient client, String ip, int port, long dur, boolean isAlive) {
boolean ss=false; boolean ss=false;
MetricBuilder builderHeartbeat = MetricBuilder.getInstance(); MetricBuilder builderHeartbeat = MetricBuilder.getInstance();
builderHeartbeat.addMetric("heartbeat") builderHeartbeat.addMetric("heartbeat")
......
package com.yingxin.prms.service.asyncTask; package com.yingxin.prms.service.asyncTask;
import com.yingxin.prms.domain.Server_Host_Info; import com.yingxin.prms.domain.Server_Host_Info;
import com.yingxin.prms.utils.SendHttpUtil;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.kairosdb.client.HttpClient; import org.kairosdb.client.HttpClient;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.apache.http.client.methods.CloseableHttpResponse;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@Component @Component
...@@ -23,7 +27,6 @@ public class HttpTask extends BasicTask{ ...@@ -23,7 +27,6 @@ public class HttpTask extends BasicTask{
private final HttpClient httpClient; private final HttpClient httpClient;
private RestTemplate restTemplate;
private static Logger logger = LoggerFactory.getLogger(HttpTask.class); private static Logger logger = LoggerFactory.getLogger(HttpTask.class);
...@@ -32,7 +35,6 @@ public class HttpTask extends BasicTask{ ...@@ -32,7 +35,6 @@ public class HttpTask extends BasicTask{
SimpleClientHttpRequestFactory httpRequestFactory = new SimpleClientHttpRequestFactory(); SimpleClientHttpRequestFactory httpRequestFactory = new SimpleClientHttpRequestFactory();
httpRequestFactory.setConnectTimeout(5000); httpRequestFactory.setConnectTimeout(5000);
httpRequestFactory.setReadTimeout(5000); httpRequestFactory.setReadTimeout(5000);
restTemplate = new RestTemplate(httpRequestFactory);
this.httpClient = httpClient; this.httpClient = httpClient;
} }
...@@ -43,21 +45,15 @@ public class HttpTask extends BasicTask{ ...@@ -43,21 +45,15 @@ public class HttpTask extends BasicTask{
*/ */
@Async("asyncTaskPool") @Async("asyncTaskPool")
public void doTask(Server_Host_Info hostInfo, ConcurrentHashMap<String, String> alarmHost) { public void doTask(Server_Host_Info hostInfo, ConcurrentHashMap<String, String> alarmHost) {
HttpEntity<String> requestEntity; Map<String,String> map = new HashMap();
ResponseEntity<String> responseEntity = null;
long dur = 0; long dur = 0;
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
try { try {
if (hostInfo.getService_method().equals("post") && !hostInfo.getCluster_name().equals("网证开通接口")) { if (hostInfo.getService_method().equals("post") && !hostInfo.getCluster_name().equals("网证开通接口")) {
HttpHeaders headers = new HttpHeaders(); map = SendHttpUtil.doPost(hostInfo.getService_path(),hostInfo.getRequest_body());
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
requestEntity = new HttpEntity<>(hostInfo.getRequest_body(), headers);
responseEntity = restTemplate.postForEntity(hostInfo.getService_path(), requestEntity, String.class);
} }
if (hostInfo.getService_method().equals("get")) { if (hostInfo.getService_method().equals("get")) {
responseEntity = restTemplate.getForEntity(hostInfo.getService_path(), String.class); map = SendHttpUtil.doGet(hostInfo.getService_path());
} }
dur = System.currentTimeMillis() - start; dur = System.currentTimeMillis() - start;
} catch (RestClientException e) { } catch (RestClientException e) {
...@@ -70,57 +66,57 @@ public class HttpTask extends BasicTask{ ...@@ -70,57 +66,57 @@ public class HttpTask extends BasicTask{
boolean flag = false; boolean flag = false;
switch (hostInfo.getCluster_name()){ switch (hostInfo.getCluster_name()){
case "VPN方式接入服务": case "VPN方式接入服务":
flag = checkStatusCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "token方式接入服务": case "token方式接入服务":
flag = checkStatusCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "日志采集服务": case "日志采集服务":
flag = checkStatusCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "核心调度服务": case "核心调度服务":
flag = checkStatusCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "token核验服务": case "token核验服务":
flag = checkStatusCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "平台业务权限配置管理服务": case "平台业务权限配置管理服务":
flag = checkStatusCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "权限核验服务facl": case "权限核验服务facl":
flag = chenkStatus(responseEntity); flag = checkStatus(map);
break; break;
case "账户应用管理服务": case "账户应用管理服务":
flag = checkStatusCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "1比1比对(图片+图片)": case "1比1比对(图片+图片)":
flag = checkCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "1比1比对(图片+特征)": case "1比1比对(图片+特征)":
flag = checkCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "1比1比对(特征+特征)": case "1比1比对(特征+特征)":
flag = checkCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "1比N比对(特征)": case "1比N比对(特征)":
flag = checkStatusCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "1比N比对(图片)": case "1比N比对(图片)":
flag = checkCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "图片生成特征值": case "图片生成特征值":
flag = checkCode(responseEntity); flag = checkStatusCode(map);
break; break;
case "依图": case "依图":
flag = checkCode(responseEntity); flag = checkCode(map);
break; break;
case "云从": case "云从":
flag = checkCode(responseEntity); flag = checkCode(map);
break; break;
default: default:
flag = checkStatusCode(responseEntity); flag = checkStatusCode(map);
} }
if (responseEntity != null) { if (map.get("body") != null && !map.get("body").isEmpty() ) {
insertToKairos(httpClient, hostInfo.getHost_ip(), hostInfo.getHost_port(), dur, flag); insertToKairos(httpClient, hostInfo.getHost_ip(), hostInfo.getHost_port(), dur, flag);
logger.info("httpTask to {}|{}", hostInfo.getHost_ip(), flag); logger.info("httpTask to {}|{}", hostInfo.getHost_ip(), flag);
if (flag) { if (flag) {
...@@ -132,24 +128,34 @@ public class HttpTask extends BasicTask{ ...@@ -132,24 +128,34 @@ public class HttpTask extends BasicTask{
} }
/* 针对不同服务集群 返回结果 作不同校验 */ /* 针对不同服务集群 返回结果 作不同校验 */
private boolean checkStatusCode(ResponseEntity<String> responseEntity) { private boolean checkStatusCode(Map<String,String> map) {
int statusCodeValue = responseEntity.getStatusCodeValue(); if(map.get("status").equals("200")){
if(statusCodeValue == 200){
return true; return true;
} }
return false; return false;
} }
private boolean checkCode(ResponseEntity<String> responseEntity) { private boolean checkCode(Map<String,String> map) {
JSONObject jsonObject = JSONObject.fromObject(responseEntity.getBody()); JSONObject jsonObject = JSONObject.fromObject( map.get("body"));
String code = jsonObject.getString("code"); if(map.containsKey("body")){
if(code.equals("0")){ String code = jsonObject.getString("code");
return true; if(code.equals("0")){
return true;
}
} }
return false; return false;
} }
private boolean checkErrorCode(ResponseEntity<String> responseEntity) { private boolean checkErrorCode(CloseableHttpResponse response) {
JSONObject jsonObject = JSONObject.fromObject(responseEntity.getBody()); JSONObject jsonObject = null;
try {
if(response == null){
return false;
}
jsonObject = JSONObject.fromObject( EntityUtils.toString(response.getEntity(),"utf-8"));
} catch (IOException e) {
e.printStackTrace();
return false;
}
String code = jsonObject.getString("error_code"); String code = jsonObject.getString("error_code");
if(code.equals("0")){ if(code.equals("0")){
return true; return true;
...@@ -157,11 +163,14 @@ public class HttpTask extends BasicTask{ ...@@ -157,11 +163,14 @@ public class HttpTask extends BasicTask{
return false; return false;
} }
private boolean chenkStatus(ResponseEntity<String> responseEntity) { private boolean checkStatus(Map<String,String> map) {
JSONObject jsonObject = JSONObject.fromObject(responseEntity.getBody()); JSONObject jsonObject = null;
String status = jsonObject.getString("status"); if(map.containsKey("body")){
if(status.equals("true")){ jsonObject = JSONObject.fromObject(map.get("body"));
return true; String status = jsonObject.getString("status");
if(status.equals("true")){
return true;
}
} }
return false; return false;
} }
......
package com.yingxin.prms.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpMessage;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/**
* Description:
* Datetime: 2020/12/1 16:15
* Author: gaozhentao
*/
public class SendHttpUtil {
public static Map<String,String> doGet(String uri) {
Map<String,String> map = new HashMap();
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 参数
StringBuffer params = new StringBuffer();
// 创建Get请求
HttpGet httpGet = new HttpGet(uri);
// 响应模型
CloseableHttpResponse response = null;
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
// 将上面的配置信息 运用到这个Get请求里
httpGet.setConfig(requestConfig);
// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
map.put("status",String.valueOf(response.getStatusLine().getStatusCode()));
if (responseEntity != null) {
map.put("body",EntityUtils.toString(responseEntity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}
public static Map<String,String> doPost(String uri, String body) {
Map<String,String> map = new HashMap();
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost(uri);
StringEntity entity = new StringEntity(body, "UTF-8");
// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
// 响应模型
CloseableHttpResponse response =null;
HttpEntity responseEntity = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
responseEntity = response.getEntity();
map.put("status",String.valueOf(response.getStatusLine().getStatusCode()));
if(responseEntity==null){
}else{
map.put("body",EntityUtils.toString(responseEntity, "utf-8"));
}
// 从响应模型中获取响应实体
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}catch (SocketException e){
e.printStackTrace();
// System.out.println("conn:"+uri);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}
}
package com.yingxin.prms.utils; package com.yingxin.prms.utils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
...@@ -41,4 +52,5 @@ public class TimeUtil { ...@@ -41,4 +52,5 @@ public class TimeUtil {
public static String getMD5Result(String password){ public static String getMD5Result(String password){
return password.substring(12,password.length()-24); return password.substring(12,password.length()-24);
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment