10萬+IT人都在關注,史上最全面的微信開發實戰教程:包含公衆號,小程序,微信支付等開發案例
歡迎關注筆者個人博客:http://blogs.chenyunkeji.com/
在微信公衆號/小程序開發過程中,後端服務要用到微信公衆平臺提供的各種接口,比如創建個性化菜單的接口,網頁授權接口,消息事件接口等,事件推送接口等,幾乎大多數的微信接口都要用到GET/POST方式的http請求,那麼就需要封裝一款通用的高效的統一請求接口,筆者把封裝好的代碼分享出來,這裏涉及到2個工具類和1個依賴jar,工具類分別是1個是信任管理器工具類,1個是具體的請求接口工具類,依賴的jar見下面的maven依賴,本案例使用Java語言,筆者相關博客中都會用到這2個工具類,需要的開發者朋友直接粘貼拿走就可用,下面直接看具體代碼:
一、引入maven依賴jar
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
二、信任管理器工具類
/**
* 創建時間:2019年3月19日 下午3:47:54
* 類說明:信任管理器工具類
* @author guobinhui
* @since JDK 1.8.0_51
*/
public class MyX509TrustManager implements X509TrustManager{
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
三、統一請求封裝
/**
* 創建時間:2019年3月19日 下午3:47:54
* 類說明:封裝統一的GET/POST請求接口
* @author guobinhui
* @since JDK 1.8.0_51
*/
public class WeiXinUtil {
private final static Logger logger= LoggerFactory.getLogger(WeiXinUtil.class);
public static JSONObject HttpGet(String URL) {
String result = null;
JSONObject jsonObj = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
// 創建httpGet.
HttpGet httpGet = new HttpGet(URL);
// 通過請求對象獲取響應對象
response = httpclient.execute(httpGet);
// 判斷網絡連接狀態碼是否正常(0--200都數正常)
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();//從HttpResponse中獲取結果
if(!StringUtils.isEmpty(entity)){
result = EntityUtils.toString(entity,"utf-8");
logger.info("請求的數據結果爲{}",result);
jsonObj = JSONObject.parseObject(result);//字符串類型轉換爲JSON對象
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonObj;
}
public static JSONObject httpPost(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 創建SSLContext對象,並使用我們指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 從上述SSLContext對象中得到SSLSocketFactory對象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 設置請求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
// 當有數據需要提交時
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意編碼格式,防止中文亂碼
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 將返回的輸入流轉換成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 釋放資源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSON.parseObject(buffer.toString());
} catch (ConnectException ce) {
logger.info("Weixin server connection timed out...");
} catch (Exception e) {
logger.info("https request error:{}.");
}
return jsonObject;
}
}
更多JavaEE資料請關注下面公衆號,歡迎廣大開發者朋友一起交流。更多微信公衆號功能演示請掃碼體驗,筆者電話(微信):18629374628