代码引用,参考文章:http://www.cnblogs.com/feiyun126/p/4778556.html,表示感谢!
1 package com.yuanchuangyun.cyb.manager.busniess.impl; 2 3 4 import java.io.IOException; 5 import java.net.SocketTimeoutException; 6 import java.net.URI; 7 import java.nio.charset.StandardCharsets; 8 import java.security.GeneralSecurityException; 9 import java.security.cert.CertificateException; 10 import java.security.cert.X509Certificate; 11 import java.util.ArrayList; 12 import java.util.List; 13 import java.util.Map; 14 import java.util.Map.Entry; 15 import java.util.Set; 16 17 import javax.net.ssl.SSLContext; 18 import javax.net.ssl.SSLException; 19 import javax.net.ssl.SSLSession; 20 import javax.net.ssl.SSLSocket; 21 22 import org.apache.commons.io.IOUtils; 23 import org.apache.commons.lang.StringUtils; 24 import org.apache.http.Consts; 25 import org.apache.http.HttpEntity; 26 import org.apache.http.HttpResponse; 27 import org.apache.http.NameValuePair; 28 import org.apache.http.client.HttpClient; 29 import org.apache.http.client.config.RequestConfig; 30 import org.apache.http.client.config.RequestConfig.Builder; 31 import org.apache.http.client.entity.UrlEncodedFormEntity; 32 import org.apache.http.client.methods.CloseableHttpResponse; 33 import org.apache.http.client.methods.HttpGet; 34 import org.apache.http.client.methods.HttpPost; 35 import org.apache.http.conn.ConnectTimeoutException; 36 import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 37 import org.apache.http.conn.ssl.SSLContextBuilder; 38 import org.apache.http.conn.ssl.TrustStrategy; 39 import org.apache.http.conn.ssl.X509HostnameVerifier; 40 import org.apache.http.entity.ContentType; 41 import org.apache.http.entity.StringEntity; 42 import org.apache.http.impl.client.CloseableHttpClient; 43 import org.apache.http.impl.client.HttpClients; 44 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 45 import org.apache.http.message.BasicNameValuePair; 46 import org.apache.http.util.EntityUtils; 47 import org.json.JSONException; 48 import org.json.JSONObject; 49 50 51 /** 52 * 依赖的jar包有:commons-lang-2.6.jar、httpclient-4.3.2.jar、httpcore-4.3.1.jar、commons-io-2.4.jar 53 * @author Renguoqiang 54 * 55 */ 56 public class WeiXinTemplateMessageService { 57 58 public static final int connTimeout=10000; 59 public static final int readTimeout=10000; 60 public static final String charset="UTF-8"; 61 private static HttpClient client = null; 62 63 static { 64 PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); 65 cm.setMaxTotal(128); 66 cm.setDefaultMaxPerRoute(128); 67 client = HttpClients.custom().setConnectionManager(cm).build(); 68 } 69 70 public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{ 71 return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout); 72 } 73 74 public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{ 75 return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout); 76 } 77 78 public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException, 79 SocketTimeoutException, Exception { 80 return postForm(url, params, null, connTimeout, readTimeout); 81 } 82 83 public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException, 84 SocketTimeoutException, Exception { 85 return postForm(url, params, null, connTimeout, readTimeout); 86 } 87 88 public static String get(String url) throws Exception { 89 return get(url, charset, null, null); 90 } 91 92 public static String get(String url, String charset) throws Exception { 93 return get(url, charset, connTimeout, readTimeout); 94 } 95 96 /** 97 * 发送一个 Post 请求, 使用指定的字符集编码. 98 * 99 * @param url 100 * @param body RequestBody 101 * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3 102 * @param charset 编码 103 * @param connTimeout 建立链接超时时间,毫秒. 104 * @param readTimeout 响应超时时间,毫秒. 105 * @return ResponseBody, 使用指定的字符集编码. 106 * @throws ConnectTimeoutException 建立链接超时异常 107 * @throws SocketTimeoutException 响应超时 108 * @throws Exception 109 */ 110 public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout) 111 throws ConnectTimeoutException, SocketTimeoutException, Exception { 112 HttpClient client = null; 113 HttpPost post = new HttpPost(url); 114 String result = ""; 115 try { 116 if (StringUtils.isNotBlank(body)) { 117 HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset)); 118 post.setEntity(entity); 119 } 120 // 设置参数 121 Builder customReqConf = RequestConfig.custom(); 122 if (connTimeout != null) { 123 customReqConf.setConnectTimeout(connTimeout); 124 } 125 if (readTimeout != null) { 126 customReqConf.setSocketTimeout(readTimeout); 127 } 128 post.setConfig(customReqConf.build()); 129 130 HttpResponse res; 131 if (url.startsWith("https")) { 132 // 执行 Https 请求. 133 client = createSSLInsecureClient(); 134 135 HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=xxxxxxxxxxxxxxx&secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxx"); 136 HttpResponse responseGet = client.execute(httpGet); 137 //System.out.println(responseGet); 138 String responseText = EntityUtils.toString(responseGet.getEntity(), StandardCharsets.UTF_8); 139 //System.out.println(responseText); 140 httpGet.releaseConnection(); 141 String access_token = ""; 142 access_token = responseText.replaceAll("(?s).*access_token\":\"", "").replaceAll("(?s)\",\"expires_in.*", ""); 143 System.out.println("access_token:"+access_token); 144 145 post.setURI(new URI(post.getURI()+access_token)); 146 147 res = client.execute(post); 148 } else { 149 // 执行 Http 请求. 150 client = WeiXinTemplateMessageService.client; 151 res = client.execute(post); 152 } 153 result = IOUtils.toString(res.getEntity().getContent(), charset); 154 } finally { 155 post.releaseConnection(); 156 if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) { 157 ((CloseableHttpClient) client).close(); 158 } 159 } 160 return result; 161 } 162 163 164 /** 165 * 提交form表单 166 * 167 * @param url 168 * @param params 169 * @param connTimeout 170 * @param readTimeout 171 * @return 172 * @throws ConnectTimeoutException 173 * @throws SocketTimeoutException 174 * @throws Exception 175 */ 176 public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException, 177 SocketTimeoutException, Exception { 178 179 HttpClient client = null; 180 HttpPost post = new HttpPost(url); 181 try { 182 if (params != null && !params.isEmpty()) { 183 List<NameValuePair> formParams = new ArrayList<org.apache.http.NameValuePair>(); 184 Set<Entry<String, String>> entrySet = params.entrySet(); 185 for (Entry<String, String> entry : entrySet) { 186 formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); 187 } 188 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8); 189 post.setEntity(entity); 190 } 191 192 if (headers != null && !headers.isEmpty()) { 193 for (Entry<String, String> entry : headers.entrySet()) { 194 post.addHeader(entry.getKey(), entry.getValue()); 195 } 196 } 197 // 设置参数 198 Builder customReqConf = RequestConfig.custom(); 199 if (connTimeout != null) { 200 customReqConf.setConnectTimeout(connTimeout); 201 } 202 if (readTimeout != null) { 203 customReqConf.setSocketTimeout(readTimeout); 204 } 205 post.setConfig(customReqConf.build()); 206 HttpResponse res = null; 207 if (url.startsWith("https")) { 208 // 执行 Https 请求. 209 client = createSSLInsecureClient(); 210 res = client.execute(post); 211 } else { 212 // 执行 Http 请求. 213 client = WeiXinTemplateMessageService.client; 214 res = client.execute(post); 215 } 216 return IOUtils.toString(res.getEntity().getContent(), "UTF-8"); 217 } finally { 218 post.releaseConnection(); 219 if (url.startsWith("https") && client != null 220 && client instanceof CloseableHttpClient) { 221 ((CloseableHttpClient) client).close(); 222 } 223 } 224 } 225 226 227 228 229 /** 230 * 发送一个 GET 请求 231 * 232 * @param url 233 * @param charset 234 * @param connTimeout 建立链接超时时间,毫秒. 235 * @param readTimeout 响应超时时间,毫秒. 236 * @return 237 * @throws ConnectTimeoutException 建立链接超时 238 * @throws SocketTimeoutException 响应超时 239 * @throws Exception 240 */ 241 public static String get(String url, String charset, Integer connTimeout,Integer readTimeout) 242 throws ConnectTimeoutException,SocketTimeoutException, Exception { 243 244 HttpClient client = null; 245 HttpGet get = new HttpGet(url); 246 String result = ""; 247 try { 248 // 设置参数 249 Builder customReqConf = RequestConfig.custom(); 250 if (connTimeout != null) { 251 customReqConf.setConnectTimeout(connTimeout); 252 } 253 if (readTimeout != null) { 254 customReqConf.setSocketTimeout(readTimeout); 255 } 256 get.setConfig(customReqConf.build()); 257 258 HttpResponse res = null; 259 260 if (url.startsWith("https")) { 261 // 执行 Https 请求. 262 client = createSSLInsecureClient(); 263 res = client.execute(get); 264 } else { 265 // 执行 Http 请求. 266 client = WeiXinTemplateMessageService.client; 267 res = client.execute(get); 268 } 269 270 result = IOUtils.toString(res.getEntity().getContent(), charset); 271 } finally { 272 get.releaseConnection(); 273 if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) { 274 ((CloseableHttpClient) client).close(); 275 } 276 } 277 return result; 278 } 279 280 281 /** 282 * 从 response 里获取 charset 283 * 284 * @param ressponse 285 * @return 286 */ 287 @SuppressWarnings("unused") 288 private static String getCharsetFromResponse(HttpResponse ressponse) { 289 // Content-Type:text/html; charset=GBK 290 if (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) { 291 String contentType = ressponse.getEntity().getContentType().getValue(); 292 if (contentType.contains("charset=")) { 293 return contentType.substring(contentType.indexOf("charset=") + 8); 294 } 295 } 296 return null; 297 } 298 299 300 301 /** 302 * 创建 SSL连接 303 * @return 304 * @throws GeneralSecurityException 305 */ 306 private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException { 307 try { 308 SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { 309 public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException { 310 return true; 311 } 312 }).build(); 313 314 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { 315 @Override 316 public boolean verify(String arg0, SSLSession arg1) { 317 return true; 318 } 319 320 @Override 321 public void verify(String host, SSLSocket ssl) 322 throws IOException { 323 } 324 325 @Override 326 public void verify(String host, X509Certificate cert) 327 throws SSLException { 328 } 329 330 @Override 331 public void verify(String host, String[] cns, 332 String[] subjectAlts) throws SSLException { 333 } 334 }); 335 336 return HttpClients.custom().setSSLSocketFactory(sslsf).build(); 337 338 } catch (GeneralSecurityException e) { 339 throw e; 340 } 341 } 342 343 public static void main(String[] args) { 344 try { 345 JSONObject jsonParam = new JSONObject(); 346 try { 347 jsonParam.put("touser","o8cOBwvAJTSPbOhOInWlb7GYdKuA"); 348 jsonParam.put("template_id","yke5zUpgAolH5FzxIj8OuzX_qQ2jAEVpFWpzkU7a59c"); 349 jsonParam.put("url","http://weixin.qq.com/download"); 350 jsonParam.put("data","{}"); 351 } catch (JSONException e) { 352 System.out.println(e); 353 e.printStackTrace(); 354 } 355 String jsonStr = jsonParam.toString(); 356 357 String str= post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=",jsonStr,"application/json", "UTF-8", 10000, 10000); 358 System.out.println(str); 359 } catch (ConnectTimeoutException e) { 360 // TODO Auto-generated catch block 361 e.printStackTrace(); 362 } catch (SocketTimeoutException e) { 363 // TODO Auto-generated catch block 364 e.printStackTrace(); 365 } catch (Exception e) { 366 // TODO Auto-generated catch block 367 e.printStackTrace(); 368 } 369 } 370 }
时间: 2024-11-08 19:51:15