微信https请求工具类
工作中用到的微信https请求工具类。
- package com.gxgrh.wechat.tools;
- import com.gxgrh.wechat.wechatapi.service.SystemApiService;
- import org.apache.http.HttpConnection;
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- import javax.net.ssl.*;
- import javax.servlet.http.HttpServletRequest;
- import java.io.*;
- import java.net.URL;
- import java.net.URLConnection;
- import java.security.cert.CertificateException;
- import java.security.cert.X509Certificate;
- import java.util.HashMap;
- import java.util.Map;
- /**发送https请求的工具类
- * Created by Administrator on 2016/9/27.
- */
- @Component
- public class HttpTool {
- @Autowired
- private IoTool ioTool;
- private static final Logger logger = LogManager.getLogger(HttpTool.class);
- /**
- * 忽视证书HostName
- */
- private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
- public boolean verify(String s, SSLSession sslsession) {
- System.out.println("WARNING: Hostname is not matched for cert.");
- return true;
- }
- };
- /**
- * Ignore Certification
- */
- private static TrustManager ignoreCertificationTrustManger = new X509TrustManager(){
- private X509Certificate[] certificates;
- public void checkClientTrusted(X509Certificate certificates[],
- String authType) throws CertificateException {
- if (this.certificates == null) {
- this.certificates = certificates;
- }
- }
- public void checkServerTrusted(X509Certificate[] ax509certificate,
- String s) throws CertificateException {
- if (this.certificates == null) {
- this.certificates = ax509certificate;
- }
- }
- public X509Certificate[] getAcceptedIssuers() {
- // TODO Auto-generated method stub
- return new java.security.cert.X509Certificate[0];
- }
- };
- public String sendSSLGetMethod(String urlString) throws Exception{
- String repString = null;
- InputStream is = null;
- HttpsURLConnection connection = null;
- try {
- URL url = new URL(urlString);
- /*
- * use ignore host name verifier
- */
- HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
- connection = (HttpsURLConnection) url.openConnection();
- // Prepare SSL Context
- TrustManager[] tm = { ignoreCertificationTrustManger };
- SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
- sslContext.init(null, tm, new java.security.SecureRandom());
- // 从上述SSLContext对象中得到SSLSocketFactory对象
- SSLSocketFactory ssf = sslContext.getSocketFactory();
- connection.setSSLSocketFactory(ssf);
- if(connection.getResponseCode() != 200){
- }
- is = connection.getInputStream();
- repString = ioTool.getStringFromInputStream(is);
- } catch (Exception ex) {
- logger.error(ex.getMessage());
- ex.printStackTrace();
- } finally {
- if(null != is){
- is.close();
- is = null;
- }
- if(null != connection){
- connection.disconnect();
- }
- }
- return repString;
- }
- public String sendSSLPostMethod(String urlString,String postData) throws Exception{
- String repString = null;
- InputStream is = null;
- HttpsURLConnection connection = null;
- try {
- URL url = new URL(urlString);
- /*
- * use ignore host name verifier
- */
- HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
- connection = (HttpsURLConnection) url.openConnection();
- connection.setDoInput(true);
- connection.setDoOutput(true);
- connection.setRequestMethod("POST");
- connection.setRequestProperty("content-type","text/json");
- connection.setRequestProperty("content-length",String.valueOf(postData.getBytes().length));
- connection.getOutputStream().write(postData.getBytes("utf-8"));
- connection.getOutputStream().flush();
- connection.getOutputStream().close();
- // Prepare SSL Context
- TrustManager[] tm = { ignoreCertificationTrustManger };
- SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
- sslContext.init(null, tm, new java.security.SecureRandom());
- // 从上述SSLContext对象中得到SSLSocketFactory对象
- SSLSocketFactory ssf = sslContext.getSocketFactory();
- connection.setSSLSocketFactory(ssf);
- if(connection.getResponseCode() != 200){
- }
- is = connection.getInputStream();
- repString = ioTool.getStringFromInputStream(is);
- } catch (Exception ex) {
- logger.error(ex.getMessage());
- ex.printStackTrace();
- } finally {
- if(null != is){
- is.close();
- is = null;
- }
- if(null != connection){
- connection.disconnect();
- }
- }
- return repString;
- }
- /**
- * 上传文件到微信服务器
- * @param urlString 上传的目标url
- * @param filePath 文件路路径
- * @Param formDataName 表单id
- * @return
- * @throws Exception
- */
- public String sendSSLMutiPartFormData(String urlString,String filePath,String formDataName) throws Exception{
- String repString = null;
- InputStream is = null;
- OutputStream out = null;
- HttpsURLConnection connection = null;
- final String BOUNDARYSTR = ""+System.currentTimeMillis();
- final String BOUNDARY = "--"+BOUNDARYSTR+"\r\n";
- try{
- File file = new File(filePath);
- if(!file.exists() || !file.isFile()){
- String errorMsg = "文件["+filePath+"]不存在。无法上传。";
- logger.error(errorMsg);
- throw new Exception(errorMsg);
- }
- URL url = new URL(urlString);
- HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
- connection = (HttpsURLConnection) url.openConnection();
- connection.setDoInput(true);
- connection.setDoOutput(true);
- connection.setUseCaches(false);
- connection.setRequestMethod("POST");
- // 设置请求头信息
- connection.setRequestProperty("Connection", "Keep-Alive");
- connection.setRequestProperty("Charset", "UTF-8");
- connection.setRequestProperty("Content-type", "multipart/form-data;boundary=" + BOUNDARYSTR);
- StringBuilder sb = new StringBuilder();
- sb.append(BOUNDARY);
- sb.append("Content-Disposition: form-data;name=\""+formDataName+"\";filename=\""
- + file.getName() + "\"\r\n");
- sb.append("Content-Type:application/octet-stream\r\n\r\n");
- byte[] head = sb.toString().getBytes("utf-8");
- // 获得输出流
- out = new DataOutputStream(connection.getOutputStream());
- // 输出表头
- out.write(head);
- // 文件正文部分
- // 把文件已流文件的方式 推入到url中
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
- int bytes = 0;
- byte[] bufferOut = new byte[1024];
- while ((bytes = bis.read(bufferOut,0,1024)) != -1) {
- out.write(bufferOut, 0, bytes);
- }
- bis.close();
- byte[] foot = ("\r\n--" + BOUNDARYSTR + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
- out.write(foot);
- out.flush();
- TrustManager[] tm = { ignoreCertificationTrustManger };
- SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
- sslContext.init(null, tm, new java.security.SecureRandom());
- // 从上述SSLContext对象中得到SSLSocketFactory对象
- SSLSocketFactory ssf = sslContext.getSocketFactory();
- connection.setSSLSocketFactory(ssf);
- if(connection.getResponseCode() != 200){
- }
- is = connection.getInputStream();
- repString = ioTool.getStringFromInputStream(is);
- }catch(Exception ex){
- logger.error(ex.getMessage());
- ex.printStackTrace();
- }finally {
- if(null != is){
- is.close();
- is = null;
- }
- if(null != connection){
- connection.disconnect();
- }
- }
- return repString;
- }
- /**
- *
- * @param urlString
- * @return
- */
- public Map<String,Object> sendSSLGetDownloadMedia(String urlString){
- String fileName = null;
- byte[] repData = null;
- InputStream is = null;
- Map<String,Object> resultInfo = null;
- HttpsURLConnection connection = null;
- try {
- URL url = new URL(urlString);
- /*
- * use ignore host name verifier
- */
- HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
- connection = (HttpsURLConnection) url.openConnection();
- // Prepare SSL Context
- TrustManager[] tm = { ignoreCertificationTrustManger };
- SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
- sslContext.init(null, tm, new java.security.SecureRandom());
- // 从上述SSLContext对象中得到SSLSocketFactory对象
- SSLSocketFactory ssf = sslContext.getSocketFactory();
- connection.setSSLSocketFactory(ssf);
- /**从以下头部数据解析出文件名
- * Content-disposition: attachment; filename="MEDIA_ID.jpg"
- */
- String contentDisposition = connection.getHeaderField("Content-disposition");
- if(contentDisposition != null){
- String[] contentDispositionArray = contentDisposition.split(";");
- for(String content:contentDispositionArray){
- if(content.contains("filename")){
- String[] contentArry = content.split("=");
- fileName = contentArry[1];
- fileName = fileName.replaceAll("\"","");
- }
- }
- }
- if(connection.getResponseCode() != 200){
- }
- is = connection.getInputStream();
- repData = this.ioTool.getByteArrayFromInputStream(is);
- resultInfo = new HashMap<String,Object>();
- resultInfo.put("fileName",fileName);
- resultInfo.put("data",repData);
- } catch (Exception ex) {
- logger.error(ex.getMessage());
- ex.printStackTrace();
- } finally {
- if(null != is){
- try{
- is.close();
- is = null;
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- if(null != connection){
- connection.disconnect();
- }
- }
- return resultInfo;
- }
- /**
- *
- * @param urlString
- * @param postData
- * @return
- */
- public Map<String,Object> sendSSLPostDownloadMedia(String urlString, String postData){
- String fileName = null;
- byte[] repData = null;
- InputStream is = null;
- Map<String,Object> resultInfo = null;
- HttpsURLConnection connection = null;
- try{
- URL url = new URL(urlString);
- /*
- * use ignore host name verifier
- */
- HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
- connection = (HttpsURLConnection) url.openConnection();
- connection.setDoInput(true);
- connection.setDoOutput(true);
- connection.setRequestMethod("POST");
- connection.setRequestProperty("content-type","text/json");
- connection.setRequestProperty("content-length",String.valueOf(postData.getBytes().length));
- connection.getOutputStream().write(postData.getBytes("utf-8"));
- connection.getOutputStream().flush();
- connection.getOutputStream().close();
- // Prepare SSL Context
- TrustManager[] tm = { ignoreCertificationTrustManger };
- SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
- sslContext.init(null, tm, new java.security.SecureRandom());
- // 从上述SSLContext对象中得到SSLSocketFactory对象
- SSLSocketFactory ssf = sslContext.getSocketFactory();
- connection.setSSLSocketFactory(ssf);
- /**从以下头部数据解析出文件名
- * Content-disposition: attachment; filename="MEDIA_ID.jpg"
- */
- String contentDisposition = connection.getHeaderField("Content-disposition");
- String[] contentDispositionArray = contentDisposition.split(";");
- for(String content:contentDispositionArray){
- if(content.contains("filename")){
- String[] contentArry = content.split("=");
- fileName = contentArry[1];
- fileName = fileName.replaceAll("\"","");
- }
- }
- if(connection.getResponseCode() != 200){
- }
- is = connection.getInputStream();
- repData = this.ioTool.getByteArrayFromInputStream(is);
- resultInfo = new HashMap<String,Object>();
- resultInfo.put("fileName",fileName);
- resultInfo.put("data",repData);
- }catch (Exception ex){
- logger.error(ex.getMessage());
- ex.printStackTrace();
- }finally {
- if(null != is){
- try{
- is.close();
- is = null;
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- if(null != connection){
- connection.disconnect();
- }
- }
- return resultInfo;
- }
- /**
- *
- * @param urlString
- * @return
- */
- public String sendGetMethod(String urlString){
- String repString = null;
- InputStream is = null;
- URLConnection connection = null;
- try {
- URL url = new URL(urlString);
- connection = url.openConnection();
- connection.setRequestProperty("accept", "*/*");
- connection.setRequestProperty("connection", "Keep-Alive");
- connection.setRequestProperty("user-agent",
- "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- is = connection.getInputStream();
- repString = ioTool.getStringFromInputStream(is);
- } catch (Exception ex) {
- logger.error(ex.getMessage());
- ex.printStackTrace();
- } finally {
- if(null != is){
- try{
- is.close();
- is = null;
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
- return repString;
- }
- /**
- *
- * @param urlString
- * @param postData
- * @return
- */
- public String sendPostMethod(String urlString, String postData){
- String repString = null;
- InputStream is = null;
- URLConnection connection = null;
- try {
- URL url = new URL(urlString);
- connection = url.openConnection();
- // 设置通用的请求属性
- connection.setRequestProperty("accept", "*/*");
- connection.setRequestProperty("connection", "Keep-Alive");
- connection.setRequestProperty("user-agent",
- "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- connection.setDoInput(true);
- connection.setDoOutput(true);
- connection.setRequestProperty("content-type","text/json");
- connection.getOutputStream().write(postData.getBytes("utf-8"));
- connection.getOutputStream().flush();
- connection.getOutputStream().close();
- connection.getOutputStream().close();
- is = connection.getInputStream();
- repString = ioTool.getStringFromInputStream(is);
- } catch (Exception ex) {
- logger.error(ex.getMessage());
- ex.printStackTrace();
- } finally {
- if(null != is){
- try{
- is.close();
- is = null;
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
- return repString;
- }
- /**
- * 判断某个请求是否是异步的
- * @param request
- * @return
- */
- public boolean isAsynchronousRequest(HttpServletRequest request){
- //Jquery的ajax请求默认会加上这个头部
- String jQueryAjaxHeader = request.getHeader("x-requested-with");
- //原生js使用ajax请加上一个头部参数请求头部:XMLHttpRequest.setRequestHeader("RequestType","AJAX");
- String customAjaxHeader = request.getHeader("RequestType");
- if(( Validate.isString(jQueryAjaxHeader) && jQueryAjaxHeader.equals("XMLHttpRequest"))
- || (Validate.isString(customAjaxHeader) && customAjaxHeader.equals("AJAX")) ){
- return true;
- }
- return false;
- }
- }
主要难点是微信需要https请求。工具类里另外还封装了post方法上传素材,post方法下载素材,get方法下载素材。
直接拷贝代码会有错误,主要是logger部分的代码和还有IoTool工具类,可以自己修改下。
微信https请求工具类的更多相关文章
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类
下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...
- Java 发送 Https 请求工具类 (兼容http)
依赖 jsoup-1.11.3.jar <dependency> <groupId>org.jsoup</groupId> <artifactId>js ...
- HttpClient发起Http/Https请求工具类
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcl ...
- Https通信工具类
记录一个在微信开发中用到的https通信工具类,以后会用到的. 用于https通信的证书信任管理器 import java.security.cert.CertificateException; im ...
- HTTP请求工具类
HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...
- 【原创】标准HTTP请求工具类
以下是个人在项目开发过程中,总结的Http请求工具类,主要包括四种: 1.处理http POST请求[XML格式.无解压]: 2.处理http GET请求[XML格式.无解压]: 3.处理http P ...
- Http请求工具类(Java原生Form+Json)
package com.tzx.cc.common.constant.util; import java.io.IOException; import java.io.InputStream; imp ...
- java jdk原生的http请求工具类
package com.base; import java.io.IOException; import java.io.InputStream; import java.io.InputStream ...
随机推荐
- python-study1 in hubei
1.安装好python后要配置环境变量(C:\Python27\Scripts---能找到pip.exe和easy_install.exe和C:\Python27---能找到python.exe) 2 ...
- redhat note
1,iptables -I INPUT 5 -m state --state NEW -p tcp --dport 80 -j ACCEPT
- rosetta2014/2015安装时出现INCLUDE(keyerror)错误,解决。
错误: KeyError: 'INCLUDE' 使编译出错 解决方法: [usrname@host source]$ vim tools/build/site.settings 注释# "i ...
- chattr的常用参数详解
chattr的常用参数详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 在实际生产环境中,有的运维工程师不得不和开发和测试打交道,在我们公司最常见的就是部署接口.每天每个人部署的 ...
- Apache与Tomcat的整合
一 Apache与Tomcat比较联系 apache支持静态页,tomcat支持动态的,比如servlet等. 一般使用apache+tomcat的话,apache只是作为一个转发,对jsp的处理是由 ...
- 使用Vue构建中(大)型应用
init 首先要起一个项目,推荐用vue-cli安装 $ npm install -g vue-cli $ vue init webpack demo $ cd demo $ npm install ...
- j2ee部分
j2ee部分 1.BS与CS的联系与区别. C/S是Client/Server的缩写.服务器通常采用高性能的PC.工作站或小型机,并采用大型数据库系统,如Oracle.Sybase.InFORMix或 ...
- Js动态获取iframe子页面的高度////////////////////////zzzz
Js动态获取iframe子页面的高度 Js动态获取iframe子页面的高度总结 问题的缘由 产品有个评论列表引用的是个iframe,高度不固定于是引发这个总结. 方法1:父级页面获取子级页面的高度 ...
- hdu 2037 今年暑假不AC
今年暑假不AC Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Sub ...
- SSO