注意:文章中除工具类外,其他私钥,appid,pushUrl等xml里面的配置信息,不能直接使用的哦!

先在坐标里面引入网络请求的坐标地址
第一步:引入网络请求工具插件,我这里用的是:okhttp3

<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>3.14.9</version></dependency>

第二步:引入封装好的工具类:OkHttpUtil

package com.yfh.sportcompetitioncoursesite.map.util;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import lombok.Builder;
import lombok.Builder.Default;
import lombok.Data;
import okhttp3.*;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import javax.net.ssl.*;
import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;/*** 基于OkHttp的网络请求封装* @author zdj* @date 2021年4月24日*/
public class OkHttpUtil {public static final int EXCEPTION_CODE = -99;public static final MediaType MediaType_Json = MediaType.parse("application/json; charset=utf-8");public static final MediaType MediaType_Form = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");public static final MediaType MediaType_File = MediaType.parse("multipart/form-data; charset=utf-8");private static RequestConfig defaultRequestConfig = RequestConfig.builder().build();// 忽略https证书验证private static X509TrustManager xtm;private static SSLContext sslContext;private static HostnameVerifier DO_NOT_VERIFY;static {createX509TrustManager();createSSLContext();createHostnameVerifier();}/******************** get from方法 start *********************/public static OkRespone<String> get(String url) {return get(url, String.class);}public static <T> OkRespone<T> get(String url, Class<T> tclass) {return get(url, null, tclass, null);}public static <T> OkRespone<T> get(String url, Map<String, String> params, Class<T> tclass) {return get(url, params, tclass, defaultRequestConfig);}public static OkRespone<String> getForm(String url, Map<String, String> params) {return get(url, params, String.class);}public static <T> OkRespone<T> get(String url, Map<String, String> params, Class<T> tclass, RequestConfig config) {Request request = buildGetRequest(url, params, config);return doExecute(request, tclass, config);}/******************** get from方法 end ***********************//******************** post from方法 start ********************/public static OkRespone<String> postForm(String url, Map<String, String> params) {return postForm(url, params, String.class);}public static <T> OkRespone<T> postForm(String url, Map<String, String> params, Class<T> tclass) {return postForm(url, params, tclass, defaultRequestConfig);}public static <T> OkRespone<T> postForm(String url, Map<String, String> params, Class<T> tclass,RequestConfig config) {Request request = buildPostFormRequest(url, params, config);return doExecute(request, tclass, config);}/******************** post from方法 end ********************//******************** post body方法 start ******************/public static OkRespone<String> post(String url) {return post(url, null);}public static OkRespone<String> post(String url, String content) {return post(url, content, String.class);}public static <T> OkRespone<T> post(String url, String content, Class<T> tclass) {return post(url, content, tclass, defaultRequestConfig);}public static <T> OkRespone<T> post(String url, String content, Class<T> tclass, RequestConfig config) {Request request = buildPostBodyRequest(url, content, config);return doExecute(request, tclass, config);}/******************** post body方法 end ******************//******************** post file方法 start ******************/public static OkRespone<String> postFile(String url, FileUploadParam param) {return postFile(url, param, String.class);}public static <T> OkRespone<T> postFile(String url, FileUploadParam param, Class<T> tclass) {return postFile(url, param, tclass, defaultRequestConfig);}public static <T> OkRespone<T> postFile(String url, FileUploadParam param, Class<T> tclass, RequestConfig config) {Request request = buildPostFileRequest(url, param, config);return doExecute(request, tclass, config);}/******************** post file方法 end ******************/private static <T> OkRespone<T> doExecute(Request request, Class<T> tclass, RequestConfig config) {OkHttpClient ok = buildOkHttpClient(request.isHttps(), config);try (Response response = ok.newCall(request).execute()) {return buildOkRespone(tclass, response);} catch (Exception e) {return OkRespone.<T>builder().code(EXCEPTION_CODE).message(e.getMessage()).build();}}@SuppressWarnings("unchecked")private static <T> OkRespone<T> buildOkRespone(final Class<T> tclass, final Response response) throws IOException {String s = response.body().string();return OkRespone.<T>builder().code(response.code()).message(response.message()).data(tclass == String.class ? (T) s : JSON.parseObject(s, tclass)).build();}/*** 创建get请求*/private static Request buildGetRequest(String url, Map<String, String> params, RequestConfig config) {Preconditions.checkNotNull(url, "url is null");if (MapUtils.isNotEmpty(params)) {StringBuilder sb = new StringBuilder(url);sb.append(url.indexOf("?") > 0 ? "&" : "?");sb.append(Joiner.on('&').useForNull(StringUtils.EMPTY).withKeyValueSeparator('=').join(params));url = sb.toString();}Request.Builder b = new Request.Builder().get().url(url);Optional.ofNullable(config.headers).ifPresent(h -> b.headers(h));return b.build();}/*** 创建post body请求*/private static Request buildPostBodyRequest(String url, String content, RequestConfig config) {RequestBody body = RequestBody.create(config.mediaType, StringUtils.trimToEmpty(content));return buildPostRequest(url, config, body);}/*** 创建post form请求*/private static Request buildPostFormRequest(String url, Map<String, String> params, RequestConfig config) {FormBody.Builder fomBuilder = new FormBody.Builder();Optional.ofNullable(params).ifPresent(p -> p.entrySet().stream().filter(e -> StringUtils.isNotEmpty(e.getValue())).forEach(e -> fomBuilder.add(e.getKey(), e.getValue())));return buildPostRequest(url, config, fomBuilder.build());}/*** 创建post file请求*/private static Request buildPostFileRequest(String url, FileUploadParam param, RequestConfig config) {RequestBody body = RequestBody.create(MediaType_File, new File(param.filePath));MultipartBody.Builder b = new MultipartBody.Builder().setType(MediaType_File);b.addFormDataPart(param.formName, param.fileName, body);Optional.ofNullable(param.params).ifPresent(p -> p.forEach((k, v) -> b.addFormDataPart(k, v)));return buildPostRequest(url, config, b.build());}private static Request buildPostRequest(String url, RequestConfig config, RequestBody body) {Preconditions.checkNotNull(url, "url is null");Preconditions.checkNotNull(config, "config is null");Request.Builder b = new Request.Builder().url(url).post(body);Optional.ofNullable(config.headers).ifPresent(h -> b.headers(h));return b.build();}/*** 创建ok连接*/private static OkHttpClient buildOkHttpClient(boolean isHttps, RequestConfig config) {OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(config.connectTimeout, TimeUnit.SECONDS).readTimeout(config.readTimeout, TimeUnit.SECONDS);if (isHttps) {builder.sslSocketFactory(sslContext.getSocketFactory(), xtm).hostnameVerifier(DO_NOT_VERIFY);}OkHttpClient ok = builder.build();return ok;}// ========忽略https证书验证 start========private static void createHostnameVerifier() {if (DO_NOT_VERIFY != null) {return;}DO_NOT_VERIFY = new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}};}private static void createX509TrustManager() {if (xtm != null) {return;}xtm = new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) {}@Overridepublic X509Certificate[] getAcceptedIssuers() {X509Certificate[] x509Certificates = new X509Certificate[0];return x509Certificates;}};}private static void createSSLContext() {if (sslContext != null) {return;}try {sslContext = SSLContext.getInstance("SSL");sslContext.init(null, new TrustManager[] { xtm }, new SecureRandom());} catch (Exception e) {// log.error("createSSLContext error", e);}}// ========忽略https证书验证 end========@Builder@Datapublic static class RequestConfig {@Defaultprivate int connectTimeout = 5;// 连接超时时间,单位秒@Defaultprivate int readTimeout = 30;@Defaultprivate MediaType mediaType = MediaType_Form;private Headers headers;}@Builder@Datapublic static class FileUploadParam {private String filePath;// 文件路径private String fileName;// 文件名称@Defaultprivate String formName = "file";// 表单名字private Map<String, String> params;}@Builder@Datapublic static class OkRespone<T> {private int code;private String message;private T data;public boolean isSuccessful() {return code >= 200 && code < 300;}}
}

第三步:封装具体的请求工具类对象:RequestUtil

package com.yfh.sportcompetitioncoursesite.map.util;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;/*** @Description: 调用外部接口处理* @Author: zdj* @Date: 2021/07/16* @version: 1.0.0*/
@Slf4j
@Component
@Configuration
public class RequestUtil {@Value("${sanwan.cd.appId}")@ApiModelProperty("appId")public String appId;@Value("${sanwan.cd.pushUrl}")@ApiModelProperty("推送地址url")public String pushUrl;@Value("${sanwan.cd.privateKey}")@ApiModelProperty("推送私钥")public String privateKey;/*** post 请求* @param method 请求方法* @param dto 参数* @return* @throws Exception*/public JSONObject post(String method, JSONObject dto) throws Exception {log.info("接口调用入参::appId" + appId);log.info("接口调用入参::privateKey::" + privateKey);log.info("接口调用入参::pushUrl::" + pushUrl);// 封装公共参数Map<String, String> params = new HashMap<String, String>();params.put("app_id", appId);params.put("method", method);params.put("format", "json");params.put("charset", "utf-8");params.put("sign_type", "RSA2");params.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));params.put("version", "1.0");params.put("biz_content", dto.toJSONString());// 对参数签名String sign = sign(params, privateKey);params.put("sign", sign);log.info("接口调用入参:方法名:{}, 请求参数:{}", method, JSON.toJSONString(params));JSONObject res = new JSONObject();res.put("code", 500);res.put("data", null);try {OkHttpUtil.OkRespone<String> okRespone = OkHttpUtil.postForm(pushUrl, params);if (ObjectUtils.isEmpty(okRespone)) {res.put("msg", "接口返回空对象!");return res;}log.info("接口出参:方法名:{}, 响应参数:{}", method, JSONObject.toJSONString(okRespone));res.put("code", okRespone.getCode());res.put("data", okRespone.getData());res.put("msg", okRespone.getMessage());return res;} catch (Exception e){e.printStackTrace();res.put("msg", e.getMessage());log.info("调用接口出错:" + e.getMessage());}return res;}/*** get 请求* @param method 请求方法* @param dto 参数* @return* @throws Exception*/public JSONObject get(String method, JSONObject dto) throws Exception {log.info("接口调用入参::appId" + appId);log.info("接口调用入参::privateKey::" + privateKey);log.info("接口调用入参::pushUrl::" + pushUrl);// 封装公共参数Map<String, String> params = new HashMap<String, String>();params.put("app_id", appId);params.put("method", method);params.put("format", "json");params.put("charset", "utf-8");params.put("sign_type", "RSA2");params.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));params.put("version", "1.0");params.put("biz_content", dto.toJSONString());// 对参数签名String sign = sign(params, privateKey);params.put("sign", sign);log.info("接口调用入参:方法名:{}, 请求参数:{}", method, JSON.toJSONString(params));JSONObject res = new JSONObject();res.put("code", 500);res.put("data", null);try {OkHttpUtil.OkRespone<String> okRespone = OkHttpUtil.getForm(pushUrl, params);if (ObjectUtils.isEmpty(okRespone)) {res.put("msg", "接口返回空对象!");return res;}log.info("接口出参:方法名:{}, 响应参数:{}", method, JSONObject.toJSONString(okRespone));res.put("code", okRespone.getCode());res.put("data", okRespone.getData());res.put("msg", okRespone.getMessage());return res;} catch (Exception e){e.printStackTrace();res.put("msg", e.getMessage());log.info("调用接口出错:" + e.getMessage());}return res;}/*** 签名生成sign值** @param params* @param key* @return*/private String sign(Map<String, String> params, String key)throws Exception{String body = buildBody(params);String sign = RSAUtils.sign(body, key);return sign;}/*** 组装待签名参数** @param params* @return*/private  String buildBody(Map<String, String> params)throws UnsupportedEncodingException {StringBuilder body = new StringBuilder();for (Map.Entry<String, String> p : new TreeMap<String, String>(params).entrySet()) {if (p.getValue() != null && !StringUtils.isEmpty(String.valueOf(p.getValue()))) {body.append("&").append(p.getKey()).append("=").append(String.valueOf(p.getValue()));}}return body.toString().substring(1);}
}

第四步:封装RSA加密工具类:RSAUtils

package com.yfh.sportcompetitioncoursesite.map.util;import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;public class RSAUtils {/** *//*** 加密算法RSA*/public static final String KEY_ALGORITHM = "RSA";/** *//*** 签名算法*/public static final String SIGNATURE_ALGORITHM = "SHA256withRSA";/** *//*** 获取公钥的key*/private static final String PUBLIC_KEY = "RSAPublicKey";/** *//*** 获取私钥的key*/private static final String PRIVATE_KEY = "RSAPrivateKey";/** *//*** RSA最大加密明文大小*/private static final int MAX_ENCRYPT_BLOCK = 117;/** *//*** RSA最大解密密文大小*/private static final int MAX_DECRYPT_BLOCK = 128;/** *//*** <p>* 生成密钥对(公钥和私钥)* </p>** @return* @throws Exception*/public static Map<String, Object> genKeyPair() throws Exception {KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);keyPairGen.initialize(1024);KeyPair keyPair = keyPairGen.generateKeyPair();RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();Map<String, Object> keyMap = new HashMap<String, Object>(2);keyMap.put(PUBLIC_KEY, publicKey);keyMap.put(PRIVATE_KEY, privateKey);return keyMap;}/** *//*** <p>* 用私钥对信息生成数字签名* </p>** @param content*            已加密数据* @param privateKey*            私钥(BASE64编码)** @return* @throws Exception*/public static String sign(String content, String privateKey) throws Exception {byte[] keyBytes = Base64.getDecoder().decode(privateKey);byte[] data = content.getBytes("UTF-8");PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);signature.initSign(privateK);signature.update(data);return encryptBASE64(signature.sign());}/** *//*** <p>* 校验数字签名* </p>** @param content*            已加密数据* @param publicKey*            公钥(BASE64编码)* @param sign*            数字签名** @return* @throws Exception**/public static boolean verify(String content, String publicKey, String sign) throws Exception {byte[] keyBytes = Base64.getDecoder().decode(publicKey);byte[] data = content.getBytes("UTF-8");X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);PublicKey publicK = keyFactory.generatePublic(keySpec);Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);signature.initVerify(publicK);signature.update(data);return signature.verify(Base64.getDecoder().decode(sign));}/** *//*** <P>* 私钥解密* </p>** @param content*            已加密数据* @param privateKey*            私钥(BASE64编码)* @return* @throws Exception*/public static String decryptByPrivateKey(String content, String privateKey) throws Exception {byte[] keyBytes = Base64.getDecoder().decode(privateKey);byte[] encryptedData = decryptBASE64(content);PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, privateK);int inputLen = encryptedData.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;// 对数据分段解密while (inputLen - offSet > 0) {if (inputLen - offSet > MAX_DECRYPT_BLOCK) {cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);} else {cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * MAX_DECRYPT_BLOCK;}byte[] decryptedData = out.toByteArray();out.close();return new String(decryptedData, "UTF-8");}/** *//*** <p>* 公钥解密* </p>** @param content*            已加密数据* @param publicKey*            公钥(BASE64编码)* @return* @throws Exception*/public static String decryptByPublicKey(String content, String publicKey) throws Exception {byte[] keyBytes = Base64.getDecoder().decode(publicKey);byte[] encryptedData = decryptBASE64(content);X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key publicK = keyFactory.generatePublic(x509KeySpec);Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.DECRYPT_MODE, publicK);int inputLen = encryptedData.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;// 对数据分段解密while (inputLen - offSet > 0) {if (inputLen - offSet > MAX_DECRYPT_BLOCK) {cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);} else {cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * MAX_DECRYPT_BLOCK;}byte[] decryptedData = out.toByteArray();out.close();return new String(decryptedData, "UTF-8");}/** *//*** <p>* 公钥加密* </p>** @param content*            源数据* @param publicKey*            公钥(BASE64编码)* @return* @throws Exception*/public static String encryptByPublicKey(String content, String publicKey) throws Exception {byte[] keyBytes = Base64.getDecoder().decode(publicKey);byte[] data = content.getBytes("UTF-8");X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key publicK = keyFactory.generatePublic(x509KeySpec);// 对数据加密Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, publicK);int inputLen = data.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;// 对数据分段加密while (inputLen - offSet > 0) {if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);} else {cache = cipher.doFinal(data, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * MAX_ENCRYPT_BLOCK;}byte[] encryptedData = out.toByteArray();out.close();// Base64加密return encryptBASE64(encryptedData);}/** *//*** <p>* 私钥加密* </p>** @param content*            源数据* @param privateKey*            私钥(BASE64编码)* @return* @throws Exception*/public static String encryptByPrivateKey(String content, String privateKey) throws Exception {byte[] keyBytes = Base64.getDecoder().decode(privateKey);byte[] data = content.getBytes("UTF-8");PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());cipher.init(Cipher.ENCRYPT_MODE, privateK);int inputLen = data.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;// 对数据分段加密while (inputLen - offSet > 0) {if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);} else {cache = cipher.doFinal(data, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * MAX_ENCRYPT_BLOCK;}byte[] encryptedData = out.toByteArray();out.close();// Base64加密return encryptBASE64(encryptedData);}/** *//*** <p>* 获取私钥* </p>** @param keyMap*            密钥对* @return* @throws Exception*/public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {Key key = (Key) keyMap.get(PRIVATE_KEY);return Base64.getEncoder().encodeToString(key.getEncoded());}/** *//*** <p>* 获取公钥* </p>** @param keyMap*            密钥对* @return* @throws Exception*/public static String getPublicKey(Map<String, Object> keyMap) throws Exception {Key key = (Key) keyMap.get(PUBLIC_KEY);return Base64.getEncoder().encodeToString(key.getEncoded());}/*** BASE64解密** @param key* @return* @throws Exception*/public static byte[] decryptBASE64(String key) throws Exception {return Base64.getDecoder().decode(key);}/*** BASE64加密** @param key* @return* @throws Exception*/public static String encryptBASE64(byte[] key) throws Exception {return Base64.getEncoder().encodeToString(key);}}

第五步:响应给前端的实体对象:Result

package com.yfh.sportcompetitioncoursesite.system.vo;import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;import java.io.Serializable;/*** @author zdj* @version 1.0* @date 2022/2/14 14:39*/
@Data
@ApiModel(value = "接口返回对象", description = "接口返回对象")
public class Result<T> implements Serializable {private static final long serialVersionUID = 1L;/*** 成功标志*/@ApiModelProperty(value = "成功标志")private boolean success = true;/*** 返回处理消息*/@ApiModelProperty(value = "返回处理消息")private String message = "";/*** 返回代码*/@ApiModelProperty(value = "返回代码")private Integer code = 0;/*** 返回数据对象 data*/@ApiModelProperty(value = "返回数据对象")private T result;/*** 时间戳*/@ApiModelProperty(value = "时间戳")private long timestamp = System.currentTimeMillis();public Result() {}/*** 兼容VUE3版token失效不跳转登录页面** @param code* @param message*/public Result(Integer code, String message) {this.code = code;this.message = message;}public Result<T> success(String message) {this.message = message;this.code = 200;this.success = true;return this;}@Deprecatedpublic static Result<Object> ok() {Result<Object> r = new Result<Object>();r.setSuccess(true);r.setCode(200);return r;}@Deprecatedpublic static Result<Object> ok(String msg) {Result<Object> r = new Result<Object>();r.setSuccess(true);r.setCode(200);r.setMessage(msg);return r;}@Deprecatedpublic static Result<Object> ok(Object data) {Result<Object> r = new Result<Object>();r.setSuccess(true);r.setCode(200);r.setResult(data);return r;}public static <T> Result<T> OK() {Result<T> r = new Result<T>();r.setSuccess(true);r.setCode(200);return r;}public static <T> Result<T> OK(String msg) {Result<T> r = new Result<T>();r.setSuccess(true);r.setCode(200);r.setMessage(msg);return r;}public static <T> Result<T> OK(T data) {Result<T> r = new Result<T>();r.setSuccess(true);r.setCode(200);r.setResult(data);return r;}public static <T> Result<T> OK(String msg, T data) {Result<T> r = new Result<T>();r.setSuccess(true);r.setCode(200);r.setMessage(msg);r.setResult(data);return r;}public static <T> Result<T> error(String msg, T data) {Result<T> r = new Result<T>();r.setSuccess(false);r.setCode(500);r.setMessage(msg);r.setResult(data);return r;}public static Result<Object> error(String msg) {return error(500, msg);}public static Result<Object> error(int code, String msg) {Result<Object> r = new Result<Object>();r.setCode(code);r.setMessage(msg);r.setSuccess(false);return r;}public Result<T> error500(String message) {this.message = message;this.code = 500;this.success = false;return this;}/*** 无权限访问返回结果*/public static Result<Object> noauth(String msg) {return error(510, msg);}@JsonIgnoreprivate String onlTable;}

第六步:封装具体的业务对应的请求实现进行推送,比如,我这里推送体育馆的场地业务数据为例:SportServiceImpl

package com.yfh.sportcompetitioncoursesite.map.service.impl;import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.yfh.sportcompetitioncoursesite.map.mapper.SiteMessageMapper;
import com.yfh.sportcompetitioncoursesite.map.po.SiteMessage;
import com.yfh.sportcompetitioncoursesite.map.util.RequestUtil;
import com.yfh.sportcompetitioncoursesite.system.constants.CacheContant;
import com.yfh.sportcompetitioncoursesite.system.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** @author zdj* @version 1.0* @date 2022/2/24 15:47*/
@Slf4j
@Service
public class SportServiceImpl {/*** 场地 mapper*/@Autowiredprivate SiteMessageMapper siteMessageMapper;/*** 新增场地* @return*/public Result saveSite(SiteMessage siteMessage) {try {siteMessage.setIsDel(CacheContant.TWO);// 先推送数据到体育局Result result = this.pushSiteToTiYuJu(siteMessage);if(result.getCode().intValue() != 200){throw new RuntimeException(result.getMessage());}String sportId = result.getMessage();siteMessage.setSportId(Convert.toInt(sportId));// 新增本地场地数据int addResult = siteMessageMapper.insert(siteMessage);if (addResult == CacheContant.ZERO) {throw new RuntimeException("新增场地失败");}} catch (Exception e) {throw new RuntimeException(e.getMessage());}return Result.OK();}/*** 推送场地数据到体育局* @param siteMessage 场地对象* @return*/public Result pushSiteToTiYuJu(SiteMessage siteMessage) {log.info("场地信息推送到体育局平台...开始");// 申请最终请求的对象JSONObject jsob = new JSONObject();/**************************封装请求参数对象**************************************/// 基础信息jsob.put("address", siteMessage.getSiteDetailPlace());       // 场馆场地地址信息jsob.put("name", siteMessage.getSiteName());               // 场馆场地名称jsob.put("openTime", siteMessage.getOpenTime());         // 开放时间信息jsob.put("photos", siteMessage.getSitePhoto());              // 场地图片(可多张),逗号隔开jsob.put("provinceCode", "330000");                          // 所在省级编码/**************************调用接口,进行推送**************************************/try {JSONObject result = new RequestUtil().post("mise.gym.updateGymData", jsob);if (result.getInteger("code").intValue() != 1000) {return Result.error(result.getString("msg"));}log.info("场地信息推送到体育局平台...结束");return Result.ok(result.getString("data"));} catch (Exception e){e.printStackTrace();log.error("场地信息推送到体育局平台出错:" + e);}return Result.error("服务繁忙,请重试!");}
}

最后注意:推送的地址,appid,私钥等,需要在xml里面进行配好哈,用测试环境和正式环境区分一下,列:

下面是dev.properties里面的推送配置信息,pro.properties里面根据自己实际情况填写

#推送场地数据到体育馆需要的配置信息
sanwan.cd.appId = 1222061594657525695803392
sanwan.cd.pushUrl = http://ww.span.ceshi.com
sanwan.cd.privateKey = IIEvQIBADANBgkhXtMHWHncbtv/8Y+376d+Ep21riQnirsORaZYOdb7CW2xjCTkfZzXX8QGncoXw2vFJKi29wi2tVJknC6/UUL3dkb+bxc8ZhL3TufzGelOPWmuE7Zi1H9AExJVv0im4jH3U7R8oNniVLl4v2AWJu9OVGSjZURhhz44UpoK5VZH6s=

注意:文章中除工具类外,其他私钥,appid,pushUrl等xml里面的配置信息,不能直接使用的哦!

java推送数据到指定的外部接口相关推荐

  1. java 推送数据给js,Node.js实现数据推送

    场景:后端更新数据推送到客户端(Java部分使用Tomcat服务器). 后端推送数据的解决方案有很多,比如轮询.Comet.WebSocket. 1. 轮询对于后端来说开发成本最低,就是按照传统的方式 ...

  2. java推送数据给安卓,java – 如何从Firebase推送通知中获取数据并将其显示在Android Activity中?...

    对不起这个noob问题,我是 android开发的新手.我目前正在开发一个项目,需要向安装了我的应用程序的 Android设备发送推送通知.我已经按照firebase的快速入门教程完成了这项工作,并在 ...

  3. sql server 数据库向java接口推送数据

    因为以前从未用数据库向java接口推送数据,所以为了实现这个demo我是一步一个脚印的踩坑啊!!! 此文章的作用以及应用场景:利用数据库主动推送数据,实现前端页面数据实时更新,替换ajax轮询机制.推 ...

  4. java sse_后端向前端推送数据 SSE java

    研究一种后端向前端推送数据的操作,叫SSE(Server-Sent Events),但是,我觉得这玩意就是轮询.算了,烦的要死,记录下这种方式把. 前端代码是vue写的,EventSource里面是后 ...

  5. java服务器推送浏览器_前端如何让服务器主动向浏览器推送数据

    前言 前面我们已经聊了ajax,它的特点是浏览器必须先发起请求,服务器才能给出对应的响应,想一想能不能让服务器主动向浏览器推送数据呢?那么这篇文章我们来聊一聊服务器推送功能. 轮询 假设你现在需要去做 ...

  6. flux服务器推消息,服务端主动推送数据,除了 WebSocket 你还能想到啥?

    原标题:服务端主动推送数据,除了 WebSocket 你还能想到啥? 来自公众号: 江南一点雨 在 上篇文章 中,松哥和大家分享了 WebFlux 的基本用法,小伙伴们已经了解到使用 WebFlux ...

  7. 滴滴夜莺02-自定义推送数据

    写在前面 collector采集的数据可以push到监控系统,一些场景下,我们需要自定义的一些数据指标比如: 线上某服务的qps 某业务的在线人数 某个接⼝的响应时间 某个⻚面的状态码(500.200 ...

  8. java推送技术_java网络编程 - java服务器推送技术系列方案实战

    前言 服务器推送技术(又名Comet)是建立在ARP基础之上的一种非常实用的技术,它广泛应用于Web端,手机APP应用端等.具体很多场景都需要此技术的支撑,包括扫码登录.扫码支付.网页支付.端到端消息 ...

  9. PHp批量推送数据太慢,PHP非阻塞批量推送数据-php教程

    明天看到论坛外面有人问如PHP何批量非梗阻向效劳器推送数据,这里大略总结下. 相干保举:<PHP教程> 一.最简略的方法: 一个剧本同时跑屡次,用参数来跑指定范畴.如果要推送10000用户 ...

最新文章

  1. 怎么将excel中的url批量转化为图片_阿里云+Power BI,轻松实现图片可视化报告(一)...
  2. 判断是否在数组中,若在输入其下标,否则输入-1
  3. opencv进阶学习笔记11:cannny边缘检测,直线检测,圆检测
  4. python 窗口程序开发课程_从零开始学Python - 第019课:使用PyCharm开发Python应用程序...
  5. 服务器存档修改,云服务器存档修改器
  6. Excel2010--在指定的范围内添加随机数
  7. linux 下自动重启tomcat的脚本(支持shell杀进程)
  8. 网易云深度学习第一课第三周编程作业
  9. ECStore在Win环境下如何运行CMD命令
  10. 附件计算器中的MC、MR、MS、M+作用
  11. java.util报错
  12. mysql 命令行执行存储过程_mysql 命令行执行存储过程
  13. JNCIS翻译文档之------接口
  14. 计算机汉字的输入方法有哪些,《计算机汉字输入方法.ppt
  15. 手机游戏游戏隐私政策
  16. GPRS学习——SGSN、GGSN、PCU
  17. Discarding record on action DISCARD on error 1403
  18. 为什么有些编程程序员需要两个显示器?
  19. 模拟不同系统不同浏览器
  20. Android智能电视焦点控制

热门文章

  1. 浅谈解析库XPath,bs4和pyquery
  2. 3-15岁孩子英文学习网站
  3. Auto.js学习笔记1:开发需要准备什么工具和编程语言知识?
  4. 程序人生 | 阿里面试小记
  5. Python爬取新浪微博评论数据,写入csv文件中
  6. 编程中的Context(上下文)
  7. 编写第一个JSP文件
  8. 真方位角计算文献汇总:球面三角形两点之间的方位
  9. 逍遥安卓 出现android,解决逍遥安卓模拟器一直卡在99%的方法
  10. ***无人驾驶***整理的apollo 入门课程