參考資料: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數(shù)據(jù)接口
*/
public static Object getURLGetContent(String urlStr) {
/** 網(wǎng)絡(luò)的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();// 因?yàn)槭莗ost昌粤,所以用httpUrl接收
// 設(shè)置參數(shù) 注意連接上后要先設(shè)置參數(shù)在做其他操作
connection.setDoInput(true);// 向互聯(lián)網(wǎng)讀取數(shù)據(jù)郁稍,設(shè)置為true
connection.setDoOutput(true);// 向互聯(lián)網(wǎng)傳遞數(shù)據(jù),設(shè)置為true
connection.setUseCaches(false);
connection.addRequestProperty("encoding", "UTF-8");
// connection.addRequestProperty("Content-Type",
// "application/www-form-urlencoded;charset=utf-8");
// 設(shè)定使用方法 必須先設(shè)置參數(shù)在做其他
connection.setRequestMethod("POST");
// 輸出流 將條件輸入到請(qǐng)求地址 注意在請(qǐng)求的時(shí)候一定是先寫入在寫出
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os,"utf-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write(paraem);// 對(duì)服務(wù)器輸出
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);
}
// 關(guān)閉流
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("數(shù)據(jù)導(dǎo)入異常");
e.printStackTrace();
}
// 轉(zhuǎn)換成json格式 返回回去
return result;
}
/**
* 帶證書請(qǐng)求
*/
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文件目錄 寫證書的項(xiàng)目路徑
try {
keyStore.load(instream, WXUtil.MCHID.toCharArray());//這里寫密碼..默認(rèn)是你的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); // 設(shè)置響應(yīng)頭信息
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; //返回后自己解析結(jié)果
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/**
* 上傳二進(jìn)制文件
* @param graphurl 接口地址
* @param file 圖片文件
* @return
*/
public static String uploadFile(String graphurl,MultipartFile file) {
String line = null;//接口返回的結(jié)果
try {
// 換行符
final String newLine = "\r\n";
final String boundaryPrefix = "--";
// 定義數(shù)據(jù)分隔線
String BOUNDARY = "========7d4a6d158c9";
// 服務(wù)器的域名
URL url = new URL(graphurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 設(shè)置為POST情
conn.setRequestMethod("POST");
// 發(fā)送POST請(qǐng)求必須設(shè)置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 設(shè)置請(qǐng)求頭參數(shù)
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);
// 文件參數(shù),photo參數(shù)名可以隨意修改
sb.append("Content-Disposition: form-data;name=\"image\";filename=\""
+ "https://api.weixin.qq.com" + "\"" + newLine);
sb.append("Content-Type:application/octet-stream");
// 參數(shù)頭設(shè)置完以后需要兩個(gè)換行籽腕,然后才是參數(shù)內(nèi)容
sb.append(newLine);
sb.append(newLine);
// 將參數(shù)頭的數(shù)據(jù)寫入到輸出流中
out.write(sb.toString().getBytes());
// 讀取文件數(shù)據(jù)
out.write(file.getBytes());
// 最后添加換行
out.write(newLine.getBytes());
// 定義最后數(shù)據(jù)分隔線爱葵,即--加上BOUNDARY再加上--施戴。
byte[] end_data = (newLine + boundaryPrefix + BOUNDARY
+ boundaryPrefix + newLine).getBytes();
// 寫上結(jié)尾標(biāo)識(shí)
out.write(end_data);
out.flush();
out.close();
// 定義BufferedReader輸入流來讀取URL的響應(yīng)
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = reader.readLine()) != null) {
return line;
}
} catch (Exception e) {
System.out.println("發(fā)送POST請(qǐng)求出現(xiàn)異常反浓!" + e);
}
return line;
}
/**
* 傳遞jsonhttp請(qǐng)求
* @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();
}
}
}
}
}