参考资料:https://blog.csdn.net/wrongyao/article/details/80250418
1.获取access_token
public static String getAccessToken(String appId,String appAecret) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appAecret;
Object result = HttpContenUtil.getURLGetContent(url);
@SuppressWarnings("unchecked")
Map<String, Object> openid = (Map<String, Object>) JSONObject.parse(result.toString());
return ObjectUtil.isEmpty(openid)?null:openid.containsKey("access_token")?openid.get("access_token").toString():null;
}
2.获取ticket
3.获取二维码
工具类
package com.ry.finance.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import com.ry.finance.util.WXUtile.WXUtil;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
public class HttpContenUtil {
/**
* get方法访问
*
* @param urlStr
* @return程序中访问http数据接口
*/
public static Object getURLGetContent(String urlStr) {
/** 网络的url地址 */
URL url = null;
/** http连接 */
// HttpURLConnection httpConn = null;
/**//** 输入流 */
BufferedReader in = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(urlStr);
in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
String str = null;
while ((str = in.readLine()) != null) {
sb.append(str);
}
} catch (Exception ex) {
System.out.println("输入异常!");
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
System.out.println("输出异常!");
}
}
// String result = sb.toString();
// JSONObject results = JSONObject.fromObject(result);
// System.out.println(result);
// return results;
return sb;
}
/**
* post 方法访问
*
* @param urls
* @param paraem
* @return
* @throws MalformedURLException
*/
public static String getURLPostContent(String urls, String paraem) {
String result = null;// 接收输出流
// 要访问的url地址
try {
URL url = new URL(urls);
// 连接访问地址
HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 因为是post,所以用httpUrl接收
// 设置参数 注意连接上后要先设置参数在做其他操作
connection.setDoInput(true);// 向互联网读取数据,设置为true
connection.setDoOutput(true);// 向互联网传递数据,设置为true
connection.setUseCaches(false);
connection.addRequestProperty("encoding", "UTF-8");
// connection.addRequestProperty("Content-Type",
// "application/www-form-urlencoded;charset=utf-8");
// 设定使用方法 必须先设置参数在做其他
connection.setRequestMethod("POST");
// 输出流 将条件输入到请求地址 注意在请求的时候一定是先写入在写出
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os,"utf-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write(paraem);// 对服务器输出
bw.flush();
bw.close();
osw.close();
os.close();
// 获取到输入输出流 包装
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
// 输入
String line;
StringBuilder builder = new StringBuilder();
while ((line = br.readLine()) != null) {
// 填充
builder.append(line);
}
// 关闭流
br.close();
isr.close();
is.close();
result = builder.toString();
System.out.println(result);
} catch (MalformedURLException e) {
System.out.println("连接失败!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("数据导入异常");
e.printStackTrace();
}
// 转换成json格式 返回回去
return result;
}
/**
* 带证书请求
*/
public static String doRefundPost(String url,String xmlData) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
// URL save = Thread.currentThread().getContextClassLoader().getResource("ftl/apiclient_cert.p12");
// String str = save.toString();
File file = ResourceUtils.getFile("classpath:ftl/apiclient_cert.p12");
FileInputStream instream = new FileInputStream(file);//P12文件目录 写证书的项目路径
try {
keyStore.load(instream, WXUtil.MCHID.toCharArray());//这里写密码..默认是你的MCHID 证书密码
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, WXUtil.MCHID.toCharArray())//这里也是写密码的
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
try {
HttpPost httpost = new HttpPost(url); // 设置响应头信息
httpost.addHeader("Connection", "keep-alive");
httpost.addHeader("Accept", "*/*");
httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
httpost.addHeader("Host", "api.mch.weixin.qq.com");
httpost.addHeader("X-Requested-With", "XMLHttpRequest");
httpost.addHeader("Cache-Control", "max-age=0");
httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
httpost.setEntity(new StringEntity(xmlData, "UTF-8"));
CloseableHttpResponse response = httpclient.execute(httpost);
try {
HttpEntity entity = response.getEntity();
String returnMessage = EntityUtils.toString(response.getEntity(), "UTF-8");
EntityUtils.consume(entity);
return returnMessage; //返回后自己解析结果
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/**
* 上传二进制文件
* @param graphurl 接口地址
* @param file 图片文件
* @return
*/
public static String uploadFile(String graphurl,MultipartFile file) {
String line = null;//接口返回的结果
try {
// 换行符
final String newLine = "\r\n";
final String boundaryPrefix = "--";
// 定义数据分隔线
String BOUNDARY = "========7d4a6d158c9";
// 服务器的域名
URL url = new URL(graphurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置为POST情
conn.setRequestMethod("POST");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求头参数
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 上传文件
StringBuilder sb = new StringBuilder();
sb.append(boundaryPrefix);
sb.append(BOUNDARY);
sb.append(newLine);
// 文件参数,photo参数名可以随意修改
sb.append("Content-Disposition: form-data;name=\"image\";filename=\""
+ "https://api.weixin.qq.com" + "\"" + newLine);
sb.append("Content-Type:application/octet-stream");
// 参数头设置完以后需要两个换行,然后才是参数内容
sb.append(newLine);
sb.append(newLine);
// 将参数头的数据写入到输出流中
out.write(sb.toString().getBytes());
// 读取文件数据
out.write(file.getBytes());
// 最后添加换行
out.write(newLine.getBytes());
// 定义最后数据分隔线,即--加上BOUNDARY再加上--。
byte[] end_data = (newLine + boundaryPrefix + BOUNDARY
+ boundaryPrefix + newLine).getBytes();
// 写上结尾标识
out.write(end_data);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = reader.readLine()) != null) {
return line;
}
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
}
return line;
}
/**
* 传递jsonhttp请求
* @param url
* @param json
* @param fileName
* @param targetPath
* @return
*/
public String httpPostWithJSON(String url, String json) {
String result = "";
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
StringEntity se = new StringEntity(json);
se.setContentType("application/json");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "UTF-8"));
httpPost.setEntity(se);
response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
InputStream instreams = resEntity.getContent();
}
}
return result;
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
} finally {
if (null != response) {
try {
response.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
}
}