耗时2天终于微信小程序成功绑定微信公众号OpenId,真的折磨人,来回测试调试接近40次
第一步:微信小程序要先配置好(手机也要授权微信公众号通知)
微信域名配置这一步很重要,你在告诉微信,你的服务器请求安全请求地址
第二步设置appid,这一步是我们要获取微信公众号openID时候要用
微信端设置好了,接下来就是小程序端这里我要解释一下原理:
首先我们要小程序跳转一个空白页面,在页面里面用<web-view> 是小程序(如微信小程序)中用于嵌入网页的组件,然后跳转java后端页面端,这里页面接收了,然后写死appid请求微信就可以了,当然这里要注意你后端页面有没有拦截,有拦截要单独放开这个页面,我们后端页面用的是element
先看小程序页面:
这是按钮订阅消息跳转空白页面
一小程序:
<view style="padding: 10px;">
<u-button type="primary" size="small" shape="circle" :plain="true" text="消息订阅"
:hairline="true" @click="wxpub"></u-button>
</view>
我要传递用户id到空白页面代码:
wxpub() {
uni.$u.route({
url: 'pages/tabbar/components/set_user/wx-pux',
params: {
userId: this.user.userId
}
})
},
以下是配置路由:
{
"root": "pages/tabbar/components/",
"pages": [
{
"path": "wx-pux",
"style": {
"navigationBarTitleText": "消息订阅"
}
}
]
}
空白页面wx-pux.vue ,我这是本地ip,改成你自己的,只能线上测成功,本地也能测,只是能测web数据传递,只能放在我最上方配置的域名的服务器:
<template>
<view class="codeH5-box">
<web-view :src="'http://192.168.10.250/wx-auth?time='+ time +'&memberId=' + encodeURI(userId)"
@message="handleWebViewMessage"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
time: new Date().getTime(),
userId: undefined,
}
},
onLoad(option) {
this.userId = option.userId
},
handleWebViewMessage: function(event) {
// 处理来自 web-view 的消息
const data = event.detail.data; // 获取消息数据
console.log('Received message from web-view:', data);
// 在这里你可以根据数据执行相应的逻辑
}
}
</script>
<style>
</style>
二、这里是后端页面(有两种方式,一种是后端页面element,还有一种自己写h5页面打包,我都会写出来)
第一种我用的element,因为我服务器linux有nginx拦截全部 "/" 没办法只能写在一起了,
首先加白名单
permission.js:
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'
NProgress.configure({ showSpinner: false })
const whiteList = ['/login', '/auth-redirect', '/bind', '/register', '/wx-auth']
router.beforeEach((to, from, next) => {
NProgress.start()
if (getToken()) {
to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
/* has token*/
if (to.path === '/login') {
next({ path: '/' })
NProgress.done()
} else {
if (store.getters.roles.length === 0) {
isRelogin.show = true
// 判断当前用户是否已拉取完user_info信息
store.dispatch('GetInfo').then(() => {
isRelogin.show = false
store.dispatch('GenerateRoutes').then(accessRoutes => {
// 根据roles权限生成可访问的路由表
router.addRoutes(accessRoutes) // 动态添加可访问路由表
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
})
}).catch(err => {
store.dispatch('LogOut').then(() => {
Message.error(err)
next({ path: '/' })
})
})
} else {
next()
}
}
} else {
// 没有token
if (whiteList.indexOf(to.path) !== -1) {
// 在免登录白名单,直接进入
next()
} else {
next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
NProgress.done()
}
}
})
router.afterEach(() => {
NProgress.done()
})
路由转页面:
// 公共路由
export const constantRoutes = [
{
path: '/redirect',
component: Layout,
hidden: true,
children: [
{
path: '/redirect/:path(.*)',
component: () => import('@/views/redirect')
}
]
},
{
path: '/wx-auth',
component: () => import('@/views/wx-pro/index'),
hidden: true
}]
permission.js 白名单
路由
三、后端接收页面(这里有主要注意点,注意看)
<template>
<div id="app">
<el-container>
<el-header class="wx-header">
<!-- 头部内容(如果需要) -->
</el-header>
<el-main class="wx-mgs">
<div class="wx-con">
<div class="icon">
<i :class="['el-icon-' + (sucBol ? 'success' : 'warning'), 'icon-large']"></i>
</div>
<div class="wx-text" id="postMessage">
{{ sucBol ? '订阅成功,1秒自动返回' : '未开通订阅' }}
</div>
<div class="btn-back">
<el-button type="primary" @click="handleBack">请点击返回</el-button>
</div>
</div>
</el-main>
</el-container>
</div>
</template>
<script>
import {codeH5Login} from "@/api/custom/index";
export default {
name: "index",
data() {
return {
code: '',
memberId: '',
sucBol: false
}
},
mounted() {
const params = new URLSearchParams(window.location.search);
const memberId = params.get('memberId');
const code = params.get('code');
this.memberId = memberId;
this.code = code;
if (this.code) {
this.setMessage()
} else {
this.getWXCode(window.location.href, 'snsapi_base')
}
},
methods: {
setMessage() {
if (!this.memberId && !this.code) {
this.$modal.msgError("缺少参数")
return
}
let params = {
gzOpenId: this.code,
userId: this.memberId
}
codeH5Login(params).then((res) => {
if (res.code == 200) {
this.sucBol = true
setTimeout(() => {
this.handleBack();
}, 2000);
} else {
this.sucBol = false
}
}).catch((err) => {
this.sucBol = false
})
},
getWXCode: async (url, snsapi) => {
let appid = '#########' //公众号的唯一标识,填写你自己的
let local = encodeURIComponent(url); //授权后重定向的回调链接地址
let time = +new Date(); //时间戳
window.location.href =
`https://open.weixin.qq.com/connect/oauth2/authorize?
appid=${appid}&
redirect_uri=${local}&
response_type=code&
scope=${snsapi}&
state=1&
time=${time}#wechat_redirect`;
},
handleBack() {
uni.webView.navigateBack()
uni.webView.postMessage({
data: {
action: 'close' //发送的消息
}
})
}
}
}
</script>
<style lang="scss" scoped>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
.wx-mgs {
width: 100%;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
.wx-con {
padding-top: 30%;
.icon {
text-align: center;
.icon-large {
font-size: 70px;
}
}
.wx-text {
padding-top: 30px;
font-size: 20px;
text-align: center;
line-height: 30px;
}
}
.btn-back {
padding-top: 20px;
}
}
}
</style>
重点element需要引入html页面不加入不能返回小程序页面
<script type="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
<script type="text/javascript">
//执行UniAppJSBridgeReady,通过后才可调用uni的api
document.addEventListener('UniAppJSBridgeReady', function() {
console.log(uni)
console.log('uni.webView', uni.webView)
uni.webView.getEnv(function(res) {
console.log('当前环境:' + JSON.stringify(res));
});
});
注意点必须加,不加返回不生效
未订阅成功
订阅成功
后端js加后端:
js:
// 修改用户公众号的微信ID
export function codeH5Login(data) {
return request({
url: '/system/custom/code',
method: 'post',
data: data
})
}
这里拿到是code,还要请求一下拿到openId:
/**
* 修改用户微信的公众号的微信ID
*/
@RepeatSubmit()
@PostMapping("/code")
@SaIgnore
public R<Void> codeH5Login(@Validated(EditGroup.class) @RequestBody SysCustom sysCustom) {
return toAjax(iSysCustomService.updateByOpenId(sysCustom));
}
service层从微信公众号tocken里面拿取openId
import me.chanjar.weixin.mp.api.WxMpService;
@Autowired
private WxMpService wxMpService;
@Override
@Transactional(rollbackFor = Exception.class)
public boolean updateByOpenId(SysCustom sysCustom) {
try {
WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(sysCustom.getGzOpenId());
sysCustom.setGzOpenId(accessToken.getOpenId());
} catch (WxErrorException e) {
log.error(e.getMessage(), e);
throw new ServiceException("获取公众号用户信息错误");
}
if(baseMapper.updateByOpenId(sysCustom)>0){
return true;
}
return false;
}
以上第一种方法完成,现在说说第二种方法h5没那么复杂两个页面搞定:
第一个页面 订阅页面
<template>
<view class="wx-mgs">
<view class="wx-con">
<view class="icon">
<icon :type="sucBol? 'success': 'warn'" size="70" />
</view>
<view class="wx-text" id="postMessage">
{{sucBol ? '订阅成功' : '未开通订阅' }}
</view>
<view class="btn-back">
<button plain="true" type="primary" @click="handleBack">点击返回小程序</button>
</view>
</view>
</view>
</template>
<script>
import utils from '@/utils/util.js'
import {
codeH5Login
} from '@/api/login.js'
export default {
data() {
return {
code: '',
memberId: '',
sucBol: false
}
},
mounted() {
const params = new URLSearchParams(window.location.search);
const memberId = params.get('memberId');
const code = params.get('code');
this.memberId = memberId;
this.code = code;
if (this.code) {
this.setMessage()
} else {
utils.getWXCode(window.location.href, 'snsapi_base')
}
},
methods: {
setMessage() {
if (!this.memberId && !this.code) {
this.$modal.msgError("缺少参数")
return
}
uni.showLoading({
title: '处理中...',
mask: true
});
const params = {
code: this.code,
memberId: this.memberId
}
codeH5Login(params).then((res) => {
if (res.code == 200) {
this.sucBol = true
} else {
this.sucBol = false
}
uni.hideLoading()
}).catch((err) => {
this.sucBol = false
uni.hideLoading()
})
},
handleBack() {
uni.webView.navigateBack()
uni.webView.postMessage({
data: {
action: 'close' //发送的消息
}
})
}
}
}
</script>
<style lang="scss">
page {
background-color: #ffffff;
.btn-back{
padding-top: 20px;
}
.wx-mgs {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
.wx-header {
.text {}
}
.wx-con {
padding-top: 30%;
.icon {
text-align: center;
}
.wx-text {
padding-top: 30px;
font-size: 20px;
text-align: center;
line-height: 30px;
}
}
}
}
</style>
第一个引入util页面对了上面那个注意点别忘了加了,html页面要加就行了,记得打报成h5,服务器nginx自己要注意
export default {
// 判断是否为微信环境
isWechat: () => {
var ua = navigator.userAgent.toLowerCase();
var isWXWork = ua.match(/wxwork/i) == 'wxwork';
var isWeixin = !isWXWork && ua.match(/MicroMessenger/i) == 'micromessenger';
return isWeixin;
},
// 获取code并登录
getWXCode: async (url, snsapi) => {
let appid = 'wx10fe97a4d9530fdd' //公众号的唯一标识
let local = encodeURIComponent(url); //授权后重定向的回调链接地址
let time = +new Date(); //时间戳
window.location.href =
`https://open.weixin.qq.com/connect/oauth2/authorize?
appid=${appid}&
redirect_uri=${local}&
response_type=code&
scope=${snsapi}&
state=1&
time=${time}#wechat_redirect`;
},
// 截取code
getUrlParam: (name) => {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
let r = window.location.search.substr(1).match(reg);
if (r != null) {
return unescape(r[2]);
}
return null;
}
}
第二步发送微信公众通知
1.配置pom。xml
<properties>
<weixin-java.version>4.3.0</weixin-java.version>
<fastjson.version>2.0.12</fastjson.version>
</properties>
<!--微信公众号-->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>${weixin-java.version}</version>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>${weixin-java.version}</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-pay</artifactId>
<version>${weixin-java.version}</version>
</dependency>
要创建配置类
image.png
WxMpProperties
package com.kyx.liantu.system.config.wx;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @ProjectName: lt365
* @Package: com.kyx.liantu.system.config.wx
* @ClassName: WxMpProperties
* @Author: qyw
* @Description: WxMpProperties
* @Date: 2024/12/26 16:49
* @Version: 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(prefix = "wx-gz")
public class WxMpProperties {
/**
* 公众号appId
*/
private String appId;
/**
* 公众号appSecret
*/
private String secret;
private String pointTemplate;
}
image.png
WechatConfiguration
package com.kyx.liantu.system.config.wx;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @ProjectName: lt365
* @Package: com.kyx.liantu.system.config.wx
* @ClassName: WechatConfiguration
* @Author: qyw
* @Description: WechatConfiguration
* @Date: 2024/12/27 9:48
* @Version: 1.0
*/
@Configuration
public class WechatConfiguration {
@Autowired
private WxMpProperties wxMpProperties;
@Bean
public WxMpService wxMpService() {
WxMpServiceImpl service = new WxMpServiceImpl();
WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
config.setAppId(wxMpProperties.getAppId());
config.setSecret(wxMpProperties.getSecret());
Map<String, WxMpConfigStorage> configMap = new HashMap<>();
configMap.put(wxMpProperties.getAppId(),config);
service.setMultiConfigStorages(configMap);
return service;
}
}
发送消息
WechatService
package com.kyx.liantu.system.config.wx;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.json.JSONObject;
import com.kyx.liantu.common.exception.ServiceException;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @ProjectName: lt365
* @Package: com.kyx.liantu.system.config.wx
* @ClassName: WechatService
* @Author: qyw
* @Description: WechatService
* @Date: 2024/12/27 9:13
* @Version: 1.0
*/
@Service
public class WechatService {
@Autowired
private WxMpProperties wxMpProperties;
@Autowired
private WxMpService mpService;
@Autowired
private WxMaService wxMaService;
public String sendMsgByTemplate(JSONObject data,String GzOpenId) {
List<WxMpTemplateData> templateDataList = new ArrayList<>();
// 遍历JSONObject的键值对
Iterator<String> keys = data.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
Object value = data.get(key);
String fieldName = key;
String fieldValue = value.toString(); // 将值转换为字符串
// 创建WxMpTemplateData对象并添加到列表中
templateDataList.add(new WxMpTemplateData(fieldName, fieldValue));
}
//构建小程序的跳转链接,是你的小程序的AppID
String appId = wxMaService.getWxMaConfig().getAppid();
//是你希望用户跳转到的小程序页面路径 miniProgram作用是微信自带可以点击微信公众号通知跳转小程序
String miniProgramPagePath = "pages/tabbar/order";
try {
WxMpTemplateMessage message = WxMpTemplateMessage.builder()
.templateId(wxMpProperties.getPointTemplate())
.toUser(GzOpenId)//公众号的OpenID
.data(templateDataList)
.miniProgram(new WxMpTemplateMessage.MiniProgram(appId, miniProgramPagePath, false))
.build();
switchService().getTemplateMsgService().sendTemplateMsg(message);
return "消费操作成功";
} catch (WxErrorException e) {
if(e.getError().getErrorCode()==43004){
return "消费操作成功,接收者未关注公众号";
}
throw new ServiceException("微信报错:" + e.getMessage());
}
}
private WxMpService switchService() {
return mpService.switchoverTo(wxMpProperties.getAppId());
}
}
http配置
package com.kyx.liantu.system.utils;
import com.kyx.liantu.common.constant.Constants;
import com.kyx.liantu.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
/**
* 通用http发送方法
*
* @author ruoyi
*/
public class HttpUtils
{
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
/**
* 向指定 URL 发送GET方法的请求
*
* @param url 发送请求的 URL
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url)
{
return sendGet(url, StringUtils.EMPTY);
}
/**
* 向指定 URL 发送GET方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param)
{
return sendGet(url, param, Constants.UTF8);
}
/**
* 向指定 URL 发送GET方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param contentType 编码类型
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param, String contentType)
{
return sendGet(url, param, contentType, true);
}
public static String sendGet(String url, String param, String contentType, boolean errorLog)
{
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try
{
String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
log.debug("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
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();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
String line;
while ((line = in.readLine()) != null)
{
result.append(line);
}
log.info("recv - {}", result);
}
catch (ConnectException e)
{
if (errorLog) {
log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
}
}
catch (SocketTimeoutException e)
{
if (errorLog) {
log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
}
}
catch (IOException e)
{
if (errorLog) {
log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
}
}
catch (Exception e)
{
if (errorLog) {
log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
}
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (Exception ex)
{
if (errorLog) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
}
return result.toString();
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param)
{
return sendPost(url, param, true);
}
public static String sendPost(String url, String param, boolean errorLog)
{
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try
{
log.info("sendPost - {}", url);
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
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("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null)
{
result.append(line);
}
log.info("recv - {}", result);
}
catch (ConnectException e)
{
if (errorLog) {
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
}
}
catch (SocketTimeoutException e)
{
if (errorLog) {
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
}
}
catch (IOException e)
{
if (errorLog) {
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
}
}
catch (Exception e)
{
if (errorLog) {
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
}
}
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
if (errorLog) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
}
return result.toString();
}
/**
* @author zl
* @description post 请求
* @param path 请求路径
* @param param 参数
* @date 2024/3/5 10:33
* @return java.lang.String
*/
public static String sendDockPost(String path, String param) {
URL url = null;
try {
url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();
os.write(param.getBytes("UTF-8"));
os.flush();
StringBuilder sb = new StringBuilder();
int httpRspCode = httpURLConnection.getResponseCode();
if (httpRspCode == HttpURLConnection.HTTP_OK) {
// 开始获取数据
BufferedReader br = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @author zl
* @description 发送创蓝短信请求
* @param path 路径
* @param param 请求参数
* @date 2022/12/29 8:55
* @return java.lang.String
*/
public static String sendSmsByPost(String path, String param) {
URL url = null;
try {
url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();
os.write(param.getBytes("UTF-8"));
os.flush();
StringBuilder sb = new StringBuilder();
int httpRspCode = httpURLConnection.getResponseCode();
if (httpRspCode == HttpURLConnection.HTTP_OK) {
// 开始获取数据
BufferedReader br = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String sendSSLPost(String url, String param)
{
StringBuilder result = new StringBuilder();
String urlNameString = url + "?" + param;
try
{
log.info("sendSSLPost - {}", urlNameString);
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
URL console = new URL(urlNameString);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
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("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret = "";
while ((ret = br.readLine()) != null)
{
if (ret != null && !"".equals(ret.trim()))
{
result.append(new String(ret.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
}
}
log.info("recv - {}", result);
conn.disconnect();
br.close();
}
catch (ConnectException e)
{
log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
}
catch (SocketTimeoutException e)
{
log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
}
catch (IOException e)
{
log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
}
catch (Exception e)
{
log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
}
return result.toString();
}
private static class TrustAnyTrustManager implements X509TrustManager
{
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
{
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
{
}
@Override
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
}
}