diff --git a/bonus-modules/bonus-material/pom.xml b/bonus-modules/bonus-material/pom.xml index c4474832..8db482ca 100644 --- a/bonus-modules/bonus-material/pom.xml +++ b/bonus-modules/bonus-material/pom.xml @@ -128,6 +128,10 @@ pdfbox 2.0.27 + + com.squareup.okhttp3 + okhttp + diff --git a/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/controller/BallController.java b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/controller/BallController.java new file mode 100644 index 00000000..9a354941 --- /dev/null +++ b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/controller/BallController.java @@ -0,0 +1,30 @@ +package com.bonus.material.basic.controller; + +import com.bonus.common.core.web.domain.AjaxResult; +import com.bonus.material.basic.domain.BallGpsEntity; +import com.bonus.material.basic.video.QxVideotape; +import lombok.extern.slf4j.Slf4j; +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; + +/** + * @author 黑子 + */ +@RestController +@RequestMapping("/ball/info/") +@Slf4j +public class BallController { + + /** + * 新增任务 + * @param puid + * @return + */ + @PostMapping("getBallGps") + public AjaxResult getBallGps(@RequestBody String puid) { + BallGpsEntity entity= QxVideotape.getBallGps(puid,null); + return AjaxResult.success(entity); + } +} diff --git a/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/domain/BallGpsEntity.java b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/domain/BallGpsEntity.java new file mode 100644 index 00000000..27d0f9de --- /dev/null +++ b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/domain/BallGpsEntity.java @@ -0,0 +1,72 @@ +package com.bonus.material.basic.domain; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; +import java.util.List; + +/** + * @author 蒋永旗 + * @create 2022/7/13 15:03 + * @Description + **/ +@NoArgsConstructor +@Data +public class BallGpsEntity implements Serializable { + private List res; + + @NoArgsConstructor + @Data + public static class ResDTO implements Serializable { + private String puid; + private String type; + private String idx; + private GPSDTO gps; + + @NoArgsConstructor + @Data + public static class GPSDTO implements Serializable { + /** + * 纬度 + **/ + private String latitude; + /** + * 经度 + **/ + private String longitude; + /** + * 方向 + **/ + private String bearing; + /** + * 速度 + **/ + private String speed; + /** + * 高度 + **/ + private String altitude; + /** + * 地区 + **/ + private String state; + /** + * 最大速度 + **/ + private String maxSpeed; + /** + * 最小速度 + **/ + private String minSpeed; + /** + * 时间 + **/ + private String utc; + /** + * 里程 + **/ + private String mileage; + } + } +} diff --git a/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/HttpClientUtil.java b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/HttpClientUtil.java new file mode 100644 index 00000000..d8f53aeb --- /dev/null +++ b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/HttpClientUtil.java @@ -0,0 +1,181 @@ +package com.bonus.material.basic.video; + +import com.alibaba.fastjson2.JSONObject; +import com.bonus.common.biz.utils.StringHelper; +import org.apache.http.HttpEntity; +import org.apache.http.HttpStatus; +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.HttpPost; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.protocol.HTTP; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.TrustStrategy; +import org.apache.http.util.EntityUtils; + +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Map; + +public class HttpClientUtil { + private static final String CHARSET = "utf-8"; + private static final String CONTENT_TYPE_TEXT_JSON = "text/json"; + + /** + * Header参数 + */ + private static final String Authorization = "Authorization"; + + private static SSLConnectionSocketFactory sslConnectionSocketFactory; + private static RequestConfig config; + + /** + * 单例实现token + */ + private String accessToken = null; + + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public void HttpClientUtils() { + initTrustHosts(); + initConfig(); + } + + private static void initTrustHosts() { + try { + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { + @Override + public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { + return true; + } + }).build(); + sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + }catch (Exception e) { + e.getStackTrace(); + } + } + + private static void initConfig() { + config = RequestConfig.custom().setConnectTimeout(10000000).setSocketTimeout(10000000).build(); + } + public String doPost(String url,String token,Map params) { + // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的) + CloseableHttpClient httpClient = HttpClientBuilder.create().build(); + HttpPost httpPost = new HttpPost(url); + // 创建json参数 + JSONObject jsonObject = new JSONObject(); + for (String key:params.keySet()){ + jsonObject.put(key,params.get(key)); + } + // 模拟表单 + //UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); + // 将user对象转换为json字符串,并放入entity中 + StringEntity entity = new StringEntity(jsonObject.toJSONString(), ContentType.APPLICATION_JSON); + // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中 + httpPost.setEntity(entity); + httpPost.setHeader("Content-Type", "application/json;charset=utf8"); + httpPost.setHeader(Authorization, "Bearer " + token); + // 响应模型 + CloseableHttpResponse response = null; + String result = null; + try { + // 由客户端执行(发送)Post请求 + response = httpClient.execute(httpPost); + // 从响应模型中获取响应实体 + HttpEntity responseEntity = response.getEntity(); + + //System.out.println("响应状态为:" + response.getStatusLine()); + if (responseEntity != null) { + result = 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 result; + } + public static String doHttpPost(String uri, JSONObject jsonObject,String token) { + CloseableHttpClient httpClient = HttpClientBuilder.create().build(); + CloseableHttpResponse response = null; + try { + HttpPost httpPost = new HttpPost(uri); + RequestConfig config = RequestConfig.custom() + //连接超时时间 + .setConnectTimeout(10*1000) + //从连接池中取的连接的最长时间 + .setConnectionRequestTimeout(6000) + //数据传输的超时时间 + .setSocketTimeout(2*60*1000) + .build(); + //设置请求配置时间 + httpPost.setConfig(config); + //装填参数 + StringEntity s = new StringEntity(jsonObject.toString(), "utf-8"); + s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); + //设置参数到请求对象中 + httpPost.setEntity(s); + httpPost.setHeader("Content-type", "application/json"); + if(StringHelper.isNotEmpty(token)){ + httpPost.setHeader("token", token); + } + httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); + response = httpClient.execute(httpPost); + + int statusCode = response.getStatusLine().getStatusCode(); + // System.out.println("statusCode:" +statusCode ); + if (HttpStatus.SC_OK == statusCode) { + HttpEntity entity = response.getEntity(); + if (null != entity) { + String resStr = EntityUtils.toString(entity, "utf-8"); + return resStr; + } + } + } catch (Exception e) { + System.out.println("CloseableHttpClient-post-请求异常:" + e.getMessage()+",case" +String.valueOf(e.getStackTrace())); + } finally { + try { + if (null != response) { + EntityUtils.consume(response.getEntity()); + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } +} + + diff --git a/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/HttpHelp.java b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/HttpHelp.java new file mode 100644 index 00000000..78169a6f --- /dev/null +++ b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/HttpHelp.java @@ -0,0 +1,220 @@ +package com.bonus.material.basic.video; + + +import org.apache.commons.io.IOUtils; + +import java.io.*; +import java.net.URL; +import java.net.URLConnection; +import java.util.List; +import java.util.Map; + +public class HttpHelp { + /** + * 向指定URL发送GET方法的请求 + * + * @param url 发送请求的URL + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @return URL 所代表远程资源的响应结果 + */ + public static String sendGet(String url, String param) { + String result = ""; + BufferedReader in = null; + try { + String urlNameString = url + "?" + param; + URL realUrl = new URL(urlNameString); + // 打开和URL之间的连接 + URLConnection connection = realUrl.openConnection(); + // 设置通用的请求属性 + connection.setRequestProperty("accept", "*/*"); + connection.setRequestProperty("connection", "Keep-Alive"); + connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + // 建立实际的连接 + connection.connect(); + // 获取所有响应头字段 + Map> map = connection.getHeaderFields(); + // 遍历所有的响应头字段 + for (String key : map.keySet()) { + System.out.println(key + "--->" + map.get(key)); + } + // 定义 BufferedReader输入流来读取URL的响应 + in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + } catch (Exception e) { + System.out.println("发送GET请求出现异常!" + e); + e.printStackTrace(); + } + // 使用finally块来关闭输入流 + finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + e2.printStackTrace(); + } + } + return result; + } + + /** + * 向指定 URL 发送POST方法的请求 + * + * @param url 发送请求的 URL + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @return 所代表远程资源的响应结果 + */ + public static String sendPost(String url, String param) { + PrintWriter out = null; + BufferedReader in = null; + String result = ""; + try { + URL realUrl = new URL(url); + // 打开和URL之间的连接 + URLConnection conn = realUrl.openConnection(); + // 设置通用的请求属性 + conn.setRequestProperty("Charsert", "UTF-8"); + conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");//设置参数类型是json格式 + conn.setRequestProperty("accept", "*/*"); + conn.setRequestProperty("connection", "Keep-Alive"); + conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + conn.setRequestProperty("key", "SonBianDian"); + conn.setRequestProperty("secret", "38fb95ccc3483d8f8226150e011a65eb067e856a"); + // 发送POST请求必须设置如下两行 + conn.setDoOutput(true); + conn.setDoInput(true); + // 获取URLConnection对象对应的输出流 + out = new PrintWriter(conn.getOutputStream()); + // 发送请求参数 + out.print(param); + // flush输出流的缓冲 + out.flush(); + // 定义BufferedReader输入流来读取URL的响应 + in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + } catch (Exception e) { + System.out.println("发送 POST 请求出现异常!" + e); + e.printStackTrace(); + } + // 使用finally块来关闭输出流、输入流 + finally { + try { + if (out != null) { + out.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + return result; + } + + /** + * 2 * 发送Http post请求 3 * 4 * @param xmlInfo 5 * json转化成的字符串 6 * @param URL 7 * + * 请求url 8 * @return 返回信息 9 + */ + public static String doHttpPost(String xmlInfo, String URL) { + InputStream instr = null; + ByteArrayOutputStream out = null; + try { + // System.out.println("发起的数据:" + xmlInfo); + byte[] xmlData = xmlInfo.getBytes("UTF-8"); +// String hexStr = ByteHelper.bytesToHexString(xmlData); +// System.out.println(hexStr); + URL url = new URL(URL); + URLConnection urlCon = url.openConnection(); + urlCon.setDoOutput(true); + urlCon.setDoInput(true); + urlCon.setUseCaches(false); + urlCon.setRequestProperty("accept", "application/json"); + urlCon.setRequestProperty("Content-Type", "application/json"); + urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length)); + urlCon.setRequestProperty("key", "SonBianDian"); + urlCon.setRequestProperty("secret", "38fb95ccc3483d8f8226150e011a65eb067e856a"); + System.out.println(String.valueOf(xmlData.length)); + DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream()); + printout.write(xmlData); + printout.flush(); + printout.close(); + instr = urlCon.getInputStream(); + byte[] bis = IOUtils.toByteArray(instr); + String ResponseString = new String(bis, "UTF-8"); + if ((ResponseString == null) || ("".equals(ResponseString.trim()))) { + System.out.println("返回空"); + } + System.out.println("返回数据为:" + ResponseString); + return ResponseString; + + } catch (Exception e) { + System.out.println("发送 POST 请求出现异常!" + e); + e.printStackTrace(); + return "0"; + } finally { + try { + if(out!= null){ + out.close(); + } + if(instr!=null){ + instr.close(); + } + } catch (Exception ex) { + } + } + } + + /** + * 2 * 发送Http post请求 3 * 4 * @param xmlInfo 5 * json转化成的字符串 6 * @param URL 7 * + * 请求url 8 * @return 返回信息 9 + */ + public static String doHttpPosts( String URL,String xmlInfo) { + // System.out.println("发起的数据:" + xmlInfo); + byte[] xmlData = xmlInfo.getBytes(); + InputStream instr = null; + ByteArrayOutputStream out = null; + try { + URL url = new URL(URL); + URLConnection urlCon = url.openConnection(); + urlCon.setDoOutput(true); + urlCon.setDoInput(true); + urlCon.setUseCaches(false); + urlCon.setRequestProperty("content-Type", "application/json"); + urlCon.setRequestProperty("charset", "utf-8"); + urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length)); + //System.out.println(String.valueOf(xmlData.length)); + DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream()); + printout.write(xmlData); + printout.flush(); + printout.close(); + instr = urlCon.getInputStream(); + byte[] bis = IOUtils.toByteArray(instr); + String ResponseString = new String(bis, "UTF-8"); + if ((ResponseString == null) || ("".equals(ResponseString.trim()))) { + System.out.println("返回空"); + } + // System.out.println("返回数据为:" + ResponseString); + return ResponseString; + + } catch (Exception e) { + e.printStackTrace(); + return null; + } finally { + try { + if(instr!=null){ + instr.close(); + } + } catch (Exception ex) { + } + } + } + + +} \ No newline at end of file diff --git a/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/QxVideotape.java b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/QxVideotape.java new file mode 100644 index 00000000..2651f50e --- /dev/null +++ b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/QxVideotape.java @@ -0,0 +1,81 @@ +package com.bonus.material.basic.video; + +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; +import com.bonus.material.basic.domain.BallGpsEntity; +import com.bonus.material.basic.video.json.JacksonHelper; +import org.springframework.stereotype.Component; + +import java.util.HashMap; + +/** + * 清新平台数据获取 + * + * @author 吕继龙 + */ +@Component +public class QxVideotape { + + private static final String LOGIN_URL2 = "login2"; + + /** + * 球机定位 + */ + private static final String GPSBALLURL = "GPS/C_GS_QueryLastGPSData"; + + /** + * 系统登录,获取token + * + * @return token + */ + public static String login() { + String json = new JacksonHelper().jsonSerialize(TVideoConfigUtil.getMaps()); + String result = HttpHelp.doHttpPosts(TVideoConfigUtil.Q2HTTP_URL + LOGIN_URL2, json); + if (result != null) { + JSONObject object = JSONObject.parseObject(result); + if (object != null) { + String token = object.getString("token"); + return token; + } else { + return null; + } + } + return null; + + } + + + + /** + * 获取球机GPS + * + * @param + * @return + **/ + public static BallGpsEntity getBallGps(String puid, String token) { + try{ + if (token == null) { + token = login(); + } + HashMap map = new HashMap<>(16); + StringBuilder strJson = new StringBuilder(); + strJson.append("{\"puid\":\"").append(puid).append("\",\"idx\": 0,\"type\":\"ST\"},"); + map.put("equipment", JSON.parse("[" + strJson.substring(0, strJson.length() - 1) + "]")); + String json = JSON.toJSONString(map); + String res = VideoHttpClient.sendPost(TVideoConfigUtil.Q2HTTP_URL + GPSBALLURL+"?token=" + token, json); + if (res.contains("Res")) { + BallGpsEntity entity = JSON.parseObject(res.toLowerCase(), BallGpsEntity.class); + return entity; + } else { + return null; + } + }catch (Exception e){ + e.printStackTrace(); + } + return null; + } + + + + +} diff --git a/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/TVideoConfigUtil.java b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/TVideoConfigUtil.java new file mode 100644 index 00000000..7e2ef80c --- /dev/null +++ b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/TVideoConfigUtil.java @@ -0,0 +1,39 @@ +package com.bonus.material.basic.video; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author 黑子 + */ +public class TVideoConfigUtil { + + /** + * 请求地址 + */ + public static String Q2HTTP_URL="http://10.138.219.3:29605/icvs2/"; + // 登录平台企业ID + + + + public static Map getMaps(){ + Map params = new HashMap<>(16); + params.put("params","VB3worGsbmwch4zo0ys17PtGbfI+UuovOO59+crbPXheSNEtZehgdpPqMTKnkMIY2GXBvmNERuNMVMsZMXF2YyTqCyMc0Rn8ygoD7GGYo3tfLi9Rh9aXqSPHc4gNhJkQ"); + return params; + } + /** + * 获取url + * @return + */ + public String getUrl(){ + try{ + return TVideoConfigUtil.Q2HTTP_URL; + }catch (Exception e){ + return null; + } + + } + + + +} diff --git a/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/VideoHttpClient.java b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/VideoHttpClient.java new file mode 100644 index 00000000..37986580 --- /dev/null +++ b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/VideoHttpClient.java @@ -0,0 +1,390 @@ +package com.bonus.material.basic.video; + + +import com.alibaba.fastjson2.JSONObject; +import com.bonus.common.biz.utils.StringHelper; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import org.apache.http.HttpResponse; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author 吕继龙 + * http请求类 + */ +public class VideoHttpClient { + static RestTemplate restTemplate; + + /** + * 生成post请求的JSON请求参数 + * 请求示例: + * { + * "id":1, + * "name":"张耀烽" + * } + * + * @return + */ + private static HttpEntity> generatePostJson(Map jsonMap, String token) { + + //如果需要其它的请求头信息、都可以在这里追加 + HttpHeaders httpHeaders = new HttpHeaders(); + + MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8"); + + if (StringHelper.isNotEmpty(token)) { + httpHeaders.add("token", token); + } + if (jsonMap == null) { + jsonMap = new HashMap<>(16); + } + + HttpEntity> httpEntity = new HttpEntity<>(jsonMap, httpHeaders); + return httpEntity; + } + + /** + * post请求、请求参数为json + * + * @return + */ + public static String sendPost(String url, String token, Map jsonMap) { + restTemplate = new RestTemplate(); + ResponseEntity apiResponse = restTemplate.postForEntity + ( + url, + generatePostJson(jsonMap, token), + String.class + ); + return apiResponse.getBody(); + } + + private static int nc = 0; + private static OkHttpClient client = new OkHttpClient().newBuilder().build(); + + /** + * 向指定URL发送GET方法的请求Authenticate + * + * @param url 发送请求的URL + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @return URL 所代表远程资源的响应结果 + */ + public static String sendGetAuthenticate(String url, String param) { + String result = ""; + BufferedReader in = null; + try { + String urlNameString = url; + URL realUrl = new URL(urlNameString); + // 打开和URL之间的连接 + URLConnection connection = realUrl.openConnection(); + // 设置通用的请求属性 + connection.setRequestProperty("accept", "*/*"); + connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); + connection.setRequestProperty("connection", "Keep-Alive"); + connection.setRequestProperty("user-agent", + "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + // 建立实际的连接 + connection.connect(); + // 获取所有响应头字段 + Map> map = connection.getHeaderFields(); + // 遍历所有的响应头字段 + result = getAuthorization(map.get("WWW-Authenticate").get(0), param, "admin", "123456", "POST"); + } catch (Exception e) { + System.out.println("发送GET请求出现异常!" + e); + e.printStackTrace(); + } + // 使用finally块来关闭输入流 + finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + e2.printStackTrace(); + } + } + return result; + } + + /** + * 向指定 URL 发送POST方法的请求 + * + * @param url 发送请求的 URL + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @return 所代表远程资源的响应结果 + */ + + public static String sendPost(String url, String param) { + String result = ""; + okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json"); + RequestBody body = RequestBody.create(mediaType, param); + Request request = new Request.Builder() + .url(url) + .method("POST", body) + .addHeader("Content-Type", "application/json") + .addHeader("Cookie", "connect.sid=s%3AJNX6IuWZL.rdxyEj7NkC4jXU645BFGtcS98rQ0%2Bibff2nUNJKRuGg") + .build(); + try { + Response response = client.newCall(request).execute(); + result = response.body().string(); + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + + /** + * 向指定 URL 发送POST方法的请求 + * + * @param url 发送请求的 URL + * @param param 请求参数 + * @param authenticate 摘要信息 + * @return 所代表远程资源的响应结果 + */ + public static String sendPostAuthenticate(String url, String param, String authenticate) { + String result = ""; + CloseableHttpClient httpClient = HttpClientBuilder.create().build(); + try { + URL realUrl = new URL(url); + HttpPost httpPost = new HttpPost(url); + // 打开和URL之间的连接 + httpPost.setHeader("Connection", "keep-alive"); + httpPost.setHeader("Authorization", authenticate); + //这里的“application/json” 可以更换因为本人是传的json参数所以用的这个 + org.apache.http.HttpEntity entityParam = new StringEntity(param, ContentType.create("application/json", "UTF-8")); + //把参数添加到post请求 + httpPost.setEntity(entityParam); + HttpResponse response = httpClient.execute(httpPost); + //获取请求对象中的响应行对象 + StatusLine statusLine = response.getStatusLine(); + int responseCode = statusLine.getStatusCode(); + if (responseCode == 200) { + //获取响应信息 + org.apache.http.HttpEntity entity = response.getEntity(); + InputStream input = entity.getContent(); + BufferedReader br = new BufferedReader(new InputStreamReader(input, "utf-8")); + result = br.readLine(); + br.close(); + input.close(); + } else { + System.out.println("响应失败"); + } + } catch (Exception e) { + System.out.println("发送 POST 请求出现异常!" + e); + e.printStackTrace(); + } + return result; + } + + /** + * @return 接口返回的json数据 + * 原理:模拟form表单提交:把请求头部信息和和img 信息 写入到输出流中, + * 通过流把img写入到服务器临时目录里,然后服务器再把img移到指定的位置 + * 最后通过写入流来获取post的响应信息。 + * @author qimh + * @description 模拟form表单,上传图片 + */ +// public static String uploadImg(String authenticate, PeopleEntity peopleEntity, String url) { +// File file = new File(CleanPathUtil.cleanString(peopleEntity.getPersonPhoto())); +// String result = ""; +// RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM) +// .addFormDataPart("image_data", file.getName(), +// RequestBody.create(okhttp3.MediaType.parse("image/jpeg"), +// file)) +// +// .addFormDataPart("groupname", peopleEntity.getMacId()) +// .addFormDataPart("label_index", peopleEntity.getFaceID()) +// .build(); +// Request request = new Request.Builder() +// .url(url) +// .method("POST", body) +// .addHeader("Authorization", authenticate) +// .build(); +// try { +// Response response = client.newCall(request).execute(); +// result = response.body().string(); +// response.close(); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// return result; +// } + + /** + * 生成授权信息 + * + * @param authorization 上一次调用返回401的WWW-Authenticate数据 + * @param username 用户名 + * @param password 密码 + * @return 授权后的数据, 应放在http头的Authorization里 + * @throws IOException 异常 + */ + private static String getAuthorization(String authorization, String uri, String username, String password, String method) throws IOException { + +// uri = StringUtils.isEmpty(uri) ? "/" : uri; +// String temp = authorization.replaceFirst("Digest", "").trim().replace("MD5", "\"MD5\""); +// String json = withdrawJson(authorization); +// JSONObject jsonObject = JSON.parseObject(json); +// //客户端随机数 +// String cnonce = Digests.generateSalt2(8); +// //认证的次数,第一次是1,第二次是2... +// String ncstr = ("00000000" + 1).substring(Integer.toString(1).length()); +// String algorithm = jsonObject.getString("algorithm"); +// String qop = jsonObject.getString("qop"); +// String nonce = jsonObject.getString("nonce"); +// String realm = jsonObject.getString("realm"); +// +// String response = Digests.http_da_calc_HA1(username, realm, DigestUtils.md5DigestAsHex(password.getBytes()), +// nonce, ncstr, cnonce, qop, +// method, uri, algorithm); +// +// //组成响应authorization +// authorization = "Digest username=\"" + username + "\"," + temp; +// authorization += ",uri=\"" + uri +// + "\",nc=\"" + ncstr +// + "\",cnonce=\"" + cnonce +// + "\",response=\"" + response + "\""; + return authorization; + } + + /** + * 将返回的Authrization信息转成json + * + * @param authorization authorization info + * @return 返回authrization json格式数据 如:String json = "{ \"realm\": \"Wowza\", \" domain\": \"/\", \" nonce\": \"MTU1NzgxMTU1NzQ4MDo2NzI3MWYxZTZkYjBiMjQ2ZGRjYTQ3ZjNiOTM2YjJjZA==\", \" algorithm\": \"MD5\", \" qop\": \"auth\" }"; + */ + private static String withdrawJson(String authorization) { + String temp = authorization.replaceFirst("Digest", "").trim().replaceAll("\"", ""); + String[] split = temp.split(","); + Map map = new HashMap<>(16); + Arrays.asList(split).forEach(c -> { + String c1 = c.replaceFirst("=", ":"); + String[] split1 = c1.split(":"); + map.put(split1[0].trim(), split1[1].trim()); + }); + return JSONObject.toJSONString(map); + } + /** + * 删除人员信息 + * @param url 地址 + * @param authorization 摘要信息 + * @param param 数据体 + * @return + **/ + public static String postDeletePerson(String url, String authorization, String param){ + String result = ""; +// okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json"); +// RequestBody body = RequestBody.create(mediaType, param); +// Request request = new Request.Builder() +// .url(url) +// .method("POST", body) +// .addHeader("Authorization", authorization) +// .build(); +// try { +// Response response = client.newCall(request).execute(); +// result = response.body().string(); +// } catch (Exception e) { +// e.printStackTrace(); +// } + return result; + } + /** + * 删除人员图片 + * @param url 地址 + * @param authorization 摘要信息 + * @param param 数据体 + * @return + **/ + public static String postDeleteImage(String url, String authorization, String param){ + String result = ""; +// okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json"); +// RequestBody body = RequestBody.create(mediaType, param); +// Request request = new Request.Builder() +// .url(url) +// .method("POST", body) +// .addHeader("Authorization", authorization) +// .build(); +// try { +// Response response = client.newCall(request).execute(); +// result = response.body().string(); +// } catch (Exception e) { +// e.printStackTrace(); +// } + return result; + } + + public static String sendGet(String url,String token, String param) { + String result = ""; + BufferedReader in = null; + + try { + String urlNameString = url + "?" + param; + URL realUrl = new URL(urlNameString); + // 打开和URL之间的连接 + URLConnection connection = realUrl.openConnection(); + // 设置通用的请求属性 + connection.setRequestProperty("accept", "*/*"); + connection.setRequestProperty("connection", "Keep-Alive"); + connection.setRequestProperty("user-agent", + "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + // 建立实际的连接 + connection.setRequestProperty("token", token); + connection.connect(); + // 获取所有响应头字段 + Map> map = connection.getHeaderFields(); + // 遍历所有的响应头字段 + for (String key : map.keySet()) { + System.out.println(key + "--->" + map.get(key)); + } + // 定义 BufferedReader输入流来读取URL的响应 + in = new BufferedReader(new InputStreamReader( + connection.getInputStream())); + String line; + while ((line = in.readLine()) != null) { + result += line; + } + } catch (Exception e) { + System.out.println("发送GET请求出现异常!" + e); + e.printStackTrace(); + } + // 使用finally块来关闭输入流 + finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception e2) { + e2.printStackTrace(); + } + } + return result; + } + + + + +} diff --git a/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/json/JacksonHelper.java b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/json/JacksonHelper.java new file mode 100644 index 00000000..ef344a00 --- /dev/null +++ b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/json/JacksonHelper.java @@ -0,0 +1,48 @@ +package com.bonus.material.basic.video.json; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; + +/** + * @author 黑子 + */ +public class JacksonHelper implements JsonHelper { + + @Override + public String jsonSerialize(Object value) { + ObjectMapper objectMapper = new ObjectMapper(); + try { + return objectMapper.writeValueAsString(value); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + @Override + @SuppressWarnings("unchecked") + public T jsonDeserialize(String value, Class tClass) { + ObjectMapper objectMapper = new ObjectMapper(); + try { + return (T) objectMapper.readValue(value, tClass); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + @SuppressWarnings("unchecked") + public T jsonDeserialize(String value, + TypeReference typeReference) { + ObjectMapper objectMapper = new ObjectMapper(); + try { + return (T) objectMapper.readValue(value, typeReference); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + +} diff --git a/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/json/JsonHelper.java b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/json/JsonHelper.java new file mode 100644 index 00000000..5952910d --- /dev/null +++ b/bonus-modules/bonus-material/src/main/java/com/bonus/material/basic/video/json/JsonHelper.java @@ -0,0 +1,9 @@ +package com.bonus.material.basic.video.json; + +public interface JsonHelper { + + public String jsonSerialize(Object value); + + public T jsonDeserialize(String value, Class tClass); + +}