微信发红包代码,解决中文乱码问题
废话不说,直接上代码。
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
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.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weixin.shop.util.Md5Encrypt;
/**
* 发送红包测试
*
* @author lenovo
*
*/
public class RedPackTest {
/**
* 红包发放接口
*/
public static final String TICKET_URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
/**
* API密钥,在商户里账户设置中API安全中的API密钥设置密钥
*/
private static String key = "357e0bf2473b7c88c6d1900abeeeeeab";
/**
* 调用发送红包接口的参数
*/
private String[] paramKeys = new String[] { "nonce_str", "sign", "mch_billno", "mch_id", "sub_mch_id", "wxappid",
"nick_name", "send_name", "re_openid", "total_amount", "min_value", "max_value", "total_num", "wishing",
"client_ip", "act_name", "remark", "logo_imgurl", "share_content", "share_url", "share_imgurl" };
public static void main(String[] args) {
try {
RedPackTest redPackTest = new RedPackTest();
String signString = redPackTest.createSignString();
System.out.println("signString=" + signString);
String sign = redPackTest.createSign(signString, key);
System.out.println("sign=" + sign);
String xml = redPackTest.createXML(sign);
System.out.println("xml=" + xml);
redPackTest.sendRedPacket(xml);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成签名字符串 <br>
* 设所有发送或者接收到的数据为集合M,<br>
* 将集合M内非空参数值的参数按照参数名ASCII码从小到大排序(字典序)<br>
* 使用URL键值对的格式(即key1=value1&key2=value2…) <br>
* 拼接成字符串stringA<br>
* 特别注意以下重要规则:<br>
* 参数名ASCII码从小到大排序(字典序);<br>
* 如果参数的值为空不参与签名;<br>
* 参数名区分大小写;<br>
* 验证调用返回或微信主动通知签名时,传送的sign参数不参与签名,将生成的签名与该sign值作校验。<br>
* 微信接口可能增加字段,验证签名时必须支持增加的扩展字段<br>
*
* @return
*/
private String createSignString() {
StringBuffer signString = new StringBuffer("");
Arrays.sort(paramKeys);
for (String param : paramKeys) {
try {
Class<?> clz = Class.forName("test.RedPack");
Object o = clz.newInstance();
Method m = clz.getMethod("get" + param.substring(0, 1).toUpperCase()
+ param.substring(1, param.length()));
String value = (String) m.invoke(o);
if (value != null && !"".equals(value)) {
signString.append(param + "=" + value + "&");
}
} catch (Exception e) {
}
}
return signString.substring(0, signString.length() - 1);
}
/**
* 生成XML
*
* @return
*/
private String createXML(String sign) {
StringBuffer signString = new StringBuffer("<xml>");
Arrays.sort(paramKeys);
for (String param : paramKeys) {
try {
Class<?> clz = Class.forName("test.RedPack");
Object o = clz.newInstance();
Method m = clz.getMethod("get" + param.substring(0, 1).toUpperCase()
+ param.substring(1, param.length()));
String value = (String) m.invoke(o);
if (value != null && !"".equals(value)) {
signString.append("<" + param + ">" + value + "</" + param + ">");
}
} catch (Exception e) {
}
}
return signString + "<sign>" + sign + "</sign></xml>";
}
/**
* 生成签名<br>
* 在stringA最后拼接上key=(API密钥的值)得到stringSignTemp字符串,<br>
* 并对stringSignTemp进行MD5运算,<br>
* 再将得到的字符串所有字符转换为大写,<br>
* 得到sign值signValue
*
* @param signString
* @param key
* @return
*/
private String createSign(String signString, String key) {
String sign = signString + "&key=" + key;
return Md5Encrypt.md5(sign).toUpperCase();
}
/**
* 发送红包
*
* @param xml
* @throws Exception
*/
public void sendRedPacket(String xml) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File("D:/apiclient_cert.p12"));
try {
keyStore.load(instream, "1234344302".toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1234344302".toCharArray()).build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpPost httpPost = new HttpPost(TICKET_URL);
System.out.println("executing request" + httpPost.getRequestLine());
//中文不成功是因为没加编码
StringEntity myEntity = new StringEntity(xml, "utf-8");
httpPost.setEntity(myEntity);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
HttpEntity entity1 = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity1 != null) {
System.out.println("Response content length: " + entity1.getContentLength());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity1.getContent()));
String text;
while ((text = bufferedReader.readLine()) != null) {
System.out.println(new String(text.getBytes("gbk"), "utf-8"));
}
}
EntityUtils.consume(entity1);
} catch (Exception e) {
e.printStackTrace();
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
如有问题,欢迎加入JEEWX技术交流群:4六六5六3182,一起研究微信开发平台!