工作中用到的微信https请求工具类。

  1. package com.gxgrh.wechat.tools;
  2.  
  3. import com.gxgrh.wechat.wechatapi.service.SystemApiService;
  4. import org.apache.http.HttpConnection;
  5. import org.apache.logging.log4j.LogManager;
  6. import org.apache.logging.log4j.Logger;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Component;
  9.  
  10. import javax.net.ssl.*;
  11. import javax.servlet.http.HttpServletRequest;
  12. import java.io.*;
  13. import java.net.URL;
  14. import java.net.URLConnection;
  15. import java.security.cert.CertificateException;
  16. import java.security.cert.X509Certificate;
  17. import java.util.HashMap;
  18. import java.util.Map;
  19.  
  20. /**发送https请求的工具类
  21. * Created by Administrator on 2016/9/27.
  22. */
  23. @Component
  24. public class HttpTool {
  25.  
  26. @Autowired
  27. private IoTool ioTool;
  28.  
  29. private static final Logger logger = LogManager.getLogger(HttpTool.class);
  30.  
  31. /**
  32. * 忽视证书HostName
  33. */
  34. private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
  35. public boolean verify(String s, SSLSession sslsession) {
  36. System.out.println("WARNING: Hostname is not matched for cert.");
  37. return true;
  38. }
  39. };
  40.  
  41. /**
  42. * Ignore Certification
  43. */
  44. private static TrustManager ignoreCertificationTrustManger = new X509TrustManager(){
  45. private X509Certificate[] certificates;
  46. public void checkClientTrusted(X509Certificate certificates[],
  47. String authType) throws CertificateException {
  48. if (this.certificates == null) {
  49. this.certificates = certificates;
  50. }
  51. }
  52. public void checkServerTrusted(X509Certificate[] ax509certificate,
  53. String s) throws CertificateException {
  54. if (this.certificates == null) {
  55. this.certificates = ax509certificate;
  56. }
  57. }
  58. public X509Certificate[] getAcceptedIssuers() {
  59. // TODO Auto-generated method stub
  60. return new java.security.cert.X509Certificate[0];
  61. }
  62. };
  63.  
  64. public String sendSSLGetMethod(String urlString) throws Exception{
  65. String repString = null;
  66. InputStream is = null;
  67. HttpsURLConnection connection = null;
  68. try {
  69.  
  70. URL url = new URL(urlString);
  71. /*
  72. * use ignore host name verifier
  73. */
  74. HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
  75. connection = (HttpsURLConnection) url.openConnection();
  76. // Prepare SSL Context
  77. TrustManager[] tm = { ignoreCertificationTrustManger };
  78. SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  79. sslContext.init(null, tm, new java.security.SecureRandom());
  80.  
  81. // 从上述SSLContext对象中得到SSLSocketFactory对象
  82. SSLSocketFactory ssf = sslContext.getSocketFactory();
  83. connection.setSSLSocketFactory(ssf);
  84. if(connection.getResponseCode() != 200){
  85.  
  86. }
  87. is = connection.getInputStream();
  88. repString = ioTool.getStringFromInputStream(is);
  89. } catch (Exception ex) {
  90. logger.error(ex.getMessage());
  91. ex.printStackTrace();
  92. } finally {
  93. if(null != is){
  94. is.close();
  95. is = null;
  96. }
  97. if(null != connection){
  98. connection.disconnect();
  99. }
  100. }
  101. return repString;
  102. }
  103.  
  104. public String sendSSLPostMethod(String urlString,String postData) throws Exception{
  105. String repString = null;
  106. InputStream is = null;
  107. HttpsURLConnection connection = null;
  108. try {
  109.  
  110. URL url = new URL(urlString);
  111. /*
  112. * use ignore host name verifier
  113. */
  114. HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
  115. connection = (HttpsURLConnection) url.openConnection();
  116. connection.setDoInput(true);
  117. connection.setDoOutput(true);
  118. connection.setRequestMethod("POST");
  119. connection.setRequestProperty("content-type","text/json");
  120. connection.setRequestProperty("content-length",String.valueOf(postData.getBytes().length));
  121. connection.getOutputStream().write(postData.getBytes("utf-8"));
  122. connection.getOutputStream().flush();
  123. connection.getOutputStream().close();
  124. // Prepare SSL Context
  125. TrustManager[] tm = { ignoreCertificationTrustManger };
  126. SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  127. sslContext.init(null, tm, new java.security.SecureRandom());
  128.  
  129. // 从上述SSLContext对象中得到SSLSocketFactory对象
  130. SSLSocketFactory ssf = sslContext.getSocketFactory();
  131. connection.setSSLSocketFactory(ssf);
  132. if(connection.getResponseCode() != 200){
  133.  
  134. }
  135. is = connection.getInputStream();
  136. repString = ioTool.getStringFromInputStream(is);
  137. } catch (Exception ex) {
  138. logger.error(ex.getMessage());
  139. ex.printStackTrace();
  140. } finally {
  141. if(null != is){
  142. is.close();
  143. is = null;
  144. }
  145. if(null != connection){
  146. connection.disconnect();
  147. }
  148. }
  149. return repString;
  150. }
  151.  
  152. /**
  153. * 上传文件到微信服务器
  154. * @param urlString 上传的目标url
  155. * @param filePath 文件路路径
  156. * @Param formDataName 表单id
  157. * @return
  158. * @throws Exception
  159. */
  160. public String sendSSLMutiPartFormData(String urlString,String filePath,String formDataName) throws Exception{
  161. String repString = null;
  162. InputStream is = null;
  163. OutputStream out = null;
  164. HttpsURLConnection connection = null;
  165. final String BOUNDARYSTR = ""+System.currentTimeMillis();
  166. final String BOUNDARY = "--"+BOUNDARYSTR+"\r\n";
  167. try{
  168. File file = new File(filePath);
  169. if(!file.exists() || !file.isFile()){
  170. String errorMsg = "文件["+filePath+"]不存在。无法上传。";
  171. logger.error(errorMsg);
  172. throw new Exception(errorMsg);
  173. }
  174. URL url = new URL(urlString);
  175. HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
  176. connection = (HttpsURLConnection) url.openConnection();
  177. connection.setDoInput(true);
  178. connection.setDoOutput(true);
  179. connection.setUseCaches(false);
  180. connection.setRequestMethod("POST");
  181. // 设置请求头信息
  182. connection.setRequestProperty("Connection", "Keep-Alive");
  183. connection.setRequestProperty("Charset", "UTF-8");
  184.  
  185. connection.setRequestProperty("Content-type", "multipart/form-data;boundary=" + BOUNDARYSTR);
  186. StringBuilder sb = new StringBuilder();
  187. sb.append(BOUNDARY);
  188. sb.append("Content-Disposition: form-data;name=\""+formDataName+"\";filename=\""
  189. + file.getName() + "\"\r\n");
  190. sb.append("Content-Type:application/octet-stream\r\n\r\n");
  191. byte[] head = sb.toString().getBytes("utf-8");
  192. // 获得输出流
  193. out = new DataOutputStream(connection.getOutputStream());
  194. // 输出表头
  195. out.write(head);
  196. // 文件正文部分
  197. // 把文件已流文件的方式 推入到url中
  198. BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
  199. int bytes = 0;
  200. byte[] bufferOut = new byte[1024];
  201. while ((bytes = bis.read(bufferOut,0,1024)) != -1) {
  202. out.write(bufferOut, 0, bytes);
  203. }
  204. bis.close();
  205. byte[] foot = ("\r\n--" + BOUNDARYSTR + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
  206. out.write(foot);
  207. out.flush();
  208. TrustManager[] tm = { ignoreCertificationTrustManger };
  209. SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  210. sslContext.init(null, tm, new java.security.SecureRandom());
  211.  
  212. // 从上述SSLContext对象中得到SSLSocketFactory对象
  213. SSLSocketFactory ssf = sslContext.getSocketFactory();
  214. connection.setSSLSocketFactory(ssf);
  215. if(connection.getResponseCode() != 200){
  216.  
  217. }
  218. is = connection.getInputStream();
  219. repString = ioTool.getStringFromInputStream(is);
  220. }catch(Exception ex){
  221. logger.error(ex.getMessage());
  222. ex.printStackTrace();
  223. }finally {
  224. if(null != is){
  225. is.close();
  226. is = null;
  227. }
  228. if(null != connection){
  229. connection.disconnect();
  230. }
  231. }
  232. return repString;
  233. }
  234.  
  235. /**
  236. *
  237. * @param urlString
  238. * @return
  239. */
  240. public Map<String,Object> sendSSLGetDownloadMedia(String urlString){
  241. String fileName = null;
  242. byte[] repData = null;
  243. InputStream is = null;
  244. Map<String,Object> resultInfo = null;
  245. HttpsURLConnection connection = null;
  246. try {
  247.  
  248. URL url = new URL(urlString);
  249. /*
  250. * use ignore host name verifier
  251. */
  252. HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
  253. connection = (HttpsURLConnection) url.openConnection();
  254. // Prepare SSL Context
  255. TrustManager[] tm = { ignoreCertificationTrustManger };
  256. SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  257. sslContext.init(null, tm, new java.security.SecureRandom());
  258.  
  259. // 从上述SSLContext对象中得到SSLSocketFactory对象
  260. SSLSocketFactory ssf = sslContext.getSocketFactory();
  261. connection.setSSLSocketFactory(ssf);
  262.  
  263. /**从以下头部数据解析出文件名
  264. * Content-disposition: attachment; filename="MEDIA_ID.jpg"
  265. */
  266. String contentDisposition = connection.getHeaderField("Content-disposition");
  267. if(contentDisposition != null){
  268. String[] contentDispositionArray = contentDisposition.split(";");
  269. for(String content:contentDispositionArray){
  270. if(content.contains("filename")){
  271. String[] contentArry = content.split("=");
  272. fileName = contentArry[1];
  273. fileName = fileName.replaceAll("\"","");
  274. }
  275. }
  276. }
  277. if(connection.getResponseCode() != 200){
  278.  
  279. }
  280. is = connection.getInputStream();
  281. repData = this.ioTool.getByteArrayFromInputStream(is);
  282. resultInfo = new HashMap<String,Object>();
  283. resultInfo.put("fileName",fileName);
  284. resultInfo.put("data",repData);
  285. } catch (Exception ex) {
  286. logger.error(ex.getMessage());
  287. ex.printStackTrace();
  288. } finally {
  289. if(null != is){
  290. try{
  291. is.close();
  292. is = null;
  293. }catch (Exception e){
  294. e.printStackTrace();
  295. }
  296.  
  297. }
  298. if(null != connection){
  299. connection.disconnect();
  300. }
  301. }
  302. return resultInfo;
  303. }
  304.  
  305. /**
  306. *
  307. * @param urlString
  308. * @param postData
  309. * @return
  310. */
  311. public Map<String,Object> sendSSLPostDownloadMedia(String urlString, String postData){
  312. String fileName = null;
  313. byte[] repData = null;
  314. InputStream is = null;
  315. Map<String,Object> resultInfo = null;
  316. HttpsURLConnection connection = null;
  317. try{
  318. URL url = new URL(urlString);
  319. /*
  320. * use ignore host name verifier
  321. */
  322. HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
  323. connection = (HttpsURLConnection) url.openConnection();
  324. connection.setDoInput(true);
  325. connection.setDoOutput(true);
  326. connection.setRequestMethod("POST");
  327. connection.setRequestProperty("content-type","text/json");
  328. connection.setRequestProperty("content-length",String.valueOf(postData.getBytes().length));
  329. connection.getOutputStream().write(postData.getBytes("utf-8"));
  330. connection.getOutputStream().flush();
  331. connection.getOutputStream().close();
  332. // Prepare SSL Context
  333. TrustManager[] tm = { ignoreCertificationTrustManger };
  334. SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  335. sslContext.init(null, tm, new java.security.SecureRandom());
  336.  
  337. // 从上述SSLContext对象中得到SSLSocketFactory对象
  338. SSLSocketFactory ssf = sslContext.getSocketFactory();
  339. connection.setSSLSocketFactory(ssf);
  340.  
  341. /**从以下头部数据解析出文件名
  342. * Content-disposition: attachment; filename="MEDIA_ID.jpg"
  343. */
  344. String contentDisposition = connection.getHeaderField("Content-disposition");
  345. String[] contentDispositionArray = contentDisposition.split(";");
  346. for(String content:contentDispositionArray){
  347. if(content.contains("filename")){
  348. String[] contentArry = content.split("=");
  349. fileName = contentArry[1];
  350. fileName = fileName.replaceAll("\"","");
  351. }
  352. }
  353. if(connection.getResponseCode() != 200){
  354.  
  355. }
  356. is = connection.getInputStream();
  357. repData = this.ioTool.getByteArrayFromInputStream(is);
  358. resultInfo = new HashMap<String,Object>();
  359. resultInfo.put("fileName",fileName);
  360. resultInfo.put("data",repData);
  361. }catch (Exception ex){
  362. logger.error(ex.getMessage());
  363. ex.printStackTrace();
  364. }finally {
  365. if(null != is){
  366. try{
  367. is.close();
  368. is = null;
  369. }catch (Exception e){
  370. e.printStackTrace();
  371. }
  372. }
  373. if(null != connection){
  374. connection.disconnect();
  375. }
  376. }
  377. return resultInfo;
  378.  
  379. }
  380.  
  381. /**
  382. *
  383. * @param urlString
  384. * @return
  385. */
  386. public String sendGetMethod(String urlString){
  387. String repString = null;
  388. InputStream is = null;
  389. URLConnection connection = null;
  390. try {
  391.  
  392. URL url = new URL(urlString);
  393. connection = url.openConnection();
  394. connection.setRequestProperty("accept", "*/*");
  395. connection.setRequestProperty("connection", "Keep-Alive");
  396. connection.setRequestProperty("user-agent",
  397. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  398.  
  399. is = connection.getInputStream();
  400. repString = ioTool.getStringFromInputStream(is);
  401. } catch (Exception ex) {
  402. logger.error(ex.getMessage());
  403. ex.printStackTrace();
  404. } finally {
  405. if(null != is){
  406. try{
  407. is.close();
  408. is = null;
  409. }catch (Exception e){
  410. e.printStackTrace();
  411. }
  412.  
  413. }
  414. }
  415. return repString;
  416. }
  417.  
  418. /**
  419. *
  420. * @param urlString
  421. * @param postData
  422. * @return
  423. */
  424. public String sendPostMethod(String urlString, String postData){
  425. String repString = null;
  426. InputStream is = null;
  427. URLConnection connection = null;
  428. try {
  429.  
  430. URL url = new URL(urlString);
  431. connection = url.openConnection();
  432. // 设置通用的请求属性
  433. connection.setRequestProperty("accept", "*/*");
  434. connection.setRequestProperty("connection", "Keep-Alive");
  435. connection.setRequestProperty("user-agent",
  436. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  437. connection.setDoInput(true);
  438. connection.setDoOutput(true);
  439. connection.setRequestProperty("content-type","text/json");
  440. connection.getOutputStream().write(postData.getBytes("utf-8"));
  441. connection.getOutputStream().flush();
  442. connection.getOutputStream().close();
  443. connection.getOutputStream().close();
  444. is = connection.getInputStream();
  445. repString = ioTool.getStringFromInputStream(is);
  446. } catch (Exception ex) {
  447. logger.error(ex.getMessage());
  448. ex.printStackTrace();
  449. } finally {
  450. if(null != is){
  451. try{
  452. is.close();
  453. is = null;
  454. }catch (Exception e){
  455. e.printStackTrace();
  456. }
  457.  
  458. }
  459. }
  460. return repString;
  461. }
  462.  
  463. /**
  464. * 判断某个请求是否是异步的
  465. * @param request
  466. * @return
  467. */
  468. public boolean isAsynchronousRequest(HttpServletRequest request){
  469.  
  470. //Jquery的ajax请求默认会加上这个头部
  471. String jQueryAjaxHeader = request.getHeader("x-requested-with");
  472. //原生js使用ajax请加上一个头部参数请求头部:XMLHttpRequest.setRequestHeader("RequestType","AJAX");
  473. String customAjaxHeader = request.getHeader("RequestType");
  474. if(( Validate.isString(jQueryAjaxHeader) && jQueryAjaxHeader.equals("XMLHttpRequest"))
  475. || (Validate.isString(customAjaxHeader) && customAjaxHeader.equals("AJAX")) ){
  476. return true;
  477. }
  478. return false;
  479. }
  480. }

主要难点是微信需要https请求。工具类里另外还封装了post方法上传素材,post方法下载素材,get方法下载素材。

直接拷贝代码会有错误,主要是logger部分的代码和还有IoTool工具类,可以自己修改下。

微信https请求工具类的更多相关文章

  1. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  2. 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

    下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...

  3. Java 发送 Https 请求工具类 (兼容http)

    依赖 jsoup-1.11.3.jar <dependency> <groupId>org.jsoup</groupId> <artifactId>js ...

  4. HttpClient发起Http/Https请求工具类

    <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcl ...

  5. Https通信工具类

    记录一个在微信开发中用到的https通信工具类,以后会用到的. 用于https通信的证书信任管理器 import java.security.cert.CertificateException; im ...

  6. HTTP请求工具类

    HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...

  7. 【原创】标准HTTP请求工具类

    以下是个人在项目开发过程中,总结的Http请求工具类,主要包括四种: 1.处理http POST请求[XML格式.无解压]: 2.处理http GET请求[XML格式.无解压]: 3.处理http P ...

  8. Http请求工具类(Java原生Form+Json)

    package com.tzx.cc.common.constant.util; import java.io.IOException; import java.io.InputStream; imp ...

  9. java jdk原生的http请求工具类

    package com.base; import java.io.IOException; import java.io.InputStream; import java.io.InputStream ...

随机推荐

  1. python-study1 in hubei

    1.安装好python后要配置环境变量(C:\Python27\Scripts---能找到pip.exe和easy_install.exe和C:\Python27---能找到python.exe) 2 ...

  2. redhat note

    1,iptables -I INPUT 5 -m state --state NEW -p tcp --dport 80 -j ACCEPT

  3. rosetta2014/2015安装时出现INCLUDE(keyerror)错误,解决。

    错误: KeyError: 'INCLUDE' 使编译出错 解决方法: [usrname@host source]$ vim tools/build/site.settings 注释# "i ...

  4. chattr的常用参数详解

    chattr的常用参数详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 在实际生产环境中,有的运维工程师不得不和开发和测试打交道,在我们公司最常见的就是部署接口.每天每个人部署的 ...

  5. Apache与Tomcat的整合

    一 Apache与Tomcat比较联系 apache支持静态页,tomcat支持动态的,比如servlet等. 一般使用apache+tomcat的话,apache只是作为一个转发,对jsp的处理是由 ...

  6. 使用Vue构建中(大)型应用

    init 首先要起一个项目,推荐用vue-cli安装 $ npm install -g vue-cli $ vue init webpack demo $ cd demo $ npm install ...

  7. j2ee部分

    j2ee部分 1.BS与CS的联系与区别. C/S是Client/Server的缩写.服务器通常采用高性能的PC.工作站或小型机,并采用大型数据库系统,如Oracle.Sybase.InFORMix或 ...

  8. Js动态获取iframe子页面的高度////////////////////////zzzz

    Js动态获取iframe子页面的高度   Js动态获取iframe子页面的高度总结 问题的缘由 产品有个评论列表引用的是个iframe,高度不固定于是引发这个总结. 方法1:父级页面获取子级页面的高度 ...

  9. hdu 2037 今年暑假不AC

    今年暑假不AC Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Sub ...

  10. SSO