#获取到的appid appid=wx7e32765bc24XXXX #获取到的AppSecret AppSecret=d58051564fe9d86093f9XXXXX
package com.cuiyongzhi.wechat.util;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/**
* ClassName: HttpUtils
*
* @Description: http请求工具类
* @author dapengniao
* @date 2016年3月10日 下午3:57:14
*/
@SuppressWarnings("deprecation")
public class HttpUtils {
/**
* @Description: http get请求共用方法
* @param @param reqUrl
* @param @param params
* @param @return
* @param @throws Exception
* @author dapengniao
* @date 2016年3月10日 下午3:57:39
*/
@SuppressWarnings("resource")
public static String sendGet(String reqUrl, Map<String, String> params)
throws Exception {
InputStream inputStream = null;
HttpGet request = new HttpGet();
try {
String url = buildUrl(reqUrl, params);
HttpClient client = new DefaultHttpClient();
request.setHeader("Accept-Encoding", "gzip");
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
inputStream = response.getEntity().getContent();
String result = getJsonStringFromGZIP(inputStream);
return result;
} finally {
if (inputStream != null) {
inputStream.close();
}
request.releaseConnection();
}
}
/**
* @Description: http post请求共用方法
* @param @param reqUrl
* @param @param params
* @param @return
* @param @throws Exception
* @author dapengniao
* @date 2016年3月10日 下午3:57:53
*/
@SuppressWarnings("resource")
public static String sendPost(String reqUrl, Map<String, String> params)
throws Exception {
try {
Set<String> set = params.keySet();
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (String key : set) {
list.add(new BasicNameValuePair(key, params.get(key)));
}
if (list.size() > 0) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(reqUrl);
request.setHeader("Accept-Encoding", "gzip");
request.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
HttpResponse response = client.execute(request);
InputStream inputStream = response.getEntity().getContent();
try {
String result = getJsonStringFromGZIP(inputStream);
return result;
} finally {
inputStream.close();
}
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("网络连接失败,请连接网络后再试");
}
} else {
throw new Exception("参数不全,请稍后重试");
}
} catch (Exception ex) {
ex.printStackTrace();
throw new Exception("发送未知异常");
}
}
/**
* @Description: http post请求json数据
* @param @param urls
* @param @param params
* @param @return
* @param @throws ClientProtocolException
* @param @throws IOException
* @author dapengniao
* @date 2016年3月10日 下午3:58:15
*/
public static String sendPostBuffer(String urls, String params)
throws ClientProtocolException, IOException {
HttpPost request = new HttpPost(urls);
StringEntity se = new StringEntity(params, HTTP.UTF_8);
request.setEntity(se);
// 发送请求
@SuppressWarnings("resource")
HttpResponse httpResponse = new DefaultHttpClient().execute(request);
// 得到应答的字符串,这也是一个 JSON 格式保存的数据
String retSrc = EntityUtils.toString(httpResponse.getEntity());
request.releaseConnection();
return retSrc;
}
/**
* @Description: http请求发送xml内容
* @param @param urlStr
* @param @param xmlInfo
* @param @return
* @author dapengniao
* @date 2016年3月10日 下午3:58:32
*/
public static String sendXmlPost(String urlStr, String xmlInfo) {
// xmlInfo xml具体字符串
try {
URL url = new URL(urlStr);
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setRequestProperty("Pragma:", "no-cache");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "text/xml");
OutputStreamWriter out = new OutputStreamWriter(
con.getOutputStream());
out.write(new String(xmlInfo.getBytes("utf-8")));
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String lines = "";
for (String line = br.readLine(); line != null; line = br
.readLine()) {
lines = lines + line;
}
return lines; // 返回请求结果
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
private static String getJsonStringFromGZIP(InputStream is) {
String jsonString = null;
try {
BufferedInputStream bis = new BufferedInputStream(is);
bis.mark(2);
// 取前两个字节
byte[] header = new byte[2];
int result = bis.read(header);
// reset输入流到开始位置
bis.reset();
// 判断是否是GZIP格式
int headerData = getShort(header);
// Gzip 流 的前两个字节是 0x1f8b
if (result != -1 && headerData == 0x1f8b) {
// LogUtil.i("HttpTask", " use GZIPInputStream ");
is = new GZIPInputStream(bis);
} else {
// LogUtil.d("HttpTask", " not use GZIPInputStream");
is = bis;
}
InputStreamReader reader = new InputStreamReader(is, "utf-8");
char[] data = new char[100];
int readSize;
StringBuffer sb = new StringBuffer();
while ((readSize = reader.read(data)) > 0) {
sb.append(data, 0, readSize);
}
jsonString = sb.toString();
bis.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonString;
}
private static int getShort(byte[] data) {
return (data[0] << 8) | data[1] & 0xFF;
}
/**
* 构建get方式的url
*
* @param reqUrl
* 基础的url地址
* @param params
* 查询参数
* @return 构建好的url
*/
public static String buildUrl(String reqUrl, Map<String, String> params) {
StringBuilder query = new StringBuilder();
Set<String> set = params.keySet();
for (String key : set) {
query.append(String.format("%s=%s&", key, params.get(key)));
}
return reqUrl + "?" + query.toString();
}
}
#获取token的url tokenUrl=https://api.weixin.qq.com/cgi-bin/token
package com.cuiyongzhi.web.start;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
/**
* ClassName: InterfaceUrlIntiServlet
* @Description: 项目启动初始化servlet
* @author dapengniao
* @date 2016年3月10日 下午4:08:43
*/
public class InterfaceUrlIntiServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void init(ServletConfig config) throws ServletException {
InterfaceUrlInti.init();
}
}
package com.cuiyongzhi.web.start;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.cuiyongzhi.web.util.GlobalConstants;
/**
* ClassName: InterfaceUrlInti
* @Description: 项目启动初始化方法
* @author dapengniao
* @date 2016年3月10日 下午4:08:21
*/
public class InterfaceUrlInti {
public synchronized static void init(){
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
if(GlobalConstants.interfaceUrlProperties==null){
GlobalConstants.interfaceUrlProperties = new Properties();
}
InputStream in = null;
try {
in = cl.getResourceAsStream("interface_url.properties");
props.load(in);
for(Object key : props.keySet()){
GlobalConstants.interfaceUrlProperties.put(key, props.get(key));
}
props = new Properties();
in = cl.getResourceAsStream("wechat.properties");
props.load(in);
for(Object key : props.keySet()){
GlobalConstants.interfaceUrlProperties.put(key, props.get(key));
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
}
package com.cuiyongzhi.wechat.common;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import com.cuiyongzhi.web.util.GlobalConstants;
import com.cuiyongzhi.wechat.util.HttpUtils;
/**
* ClassName: WeChatTask
* @Description: 微信两小时定时任务体
* @author dapengniao
* @date 2016年3月10日 下午1:42:29
*/
public class WeChatTask {
/**
* @Description: 任务执行体
* @param @throws Exception
* @author dapengniao
* @date 2016年3月10日 下午2:04:37
*/
public void getToken_getTicket() throws Exception {
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "client_credential");
params.put("appid", GlobalConstants.getInterfaceUrl("appid"));
params.put("secret", GlobalConstants.getInterfaceUrl("AppSecret"));
String jstoken = HttpUtils.sendGet(
GlobalConstants.getInterfaceUrl("tokenUrl"), params);
String access_token = JSONObject.fromObject(jstoken).getString(
"access_token"); // 获取到token并赋值保存
GlobalConstants.interfaceUrlProperties.put("access_token", access_token);
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"token为=============================="+access_token);
}
}
package com.cuiyongzhi.wechat.quartz;
import org.apache.log4j.Logger;
import com.cuiyongzhi.wechat.common.WeChatTask;
public class QuartzJob{
private static Logger logger = Logger.getLogger(QuartzJob.class);
/**
* @Description: 任务执行获取token
* @param
* @author dapengniao
* @date 2016年3月10日 下午4:34:26
*/
public void workForToken() {
try {
WeChatTask timer = new WeChatTask();
timer.getToken_getTicket();
} catch (Exception e) {
logger.error(e, e);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 要调用的工作类 -->
<bean id="quartzJob" class="com.cuiyongzhi.wechat.quartz.QuartzJob"></bean>
<!-- 定义调用对象和调用对象的方法 -->
<bean id="jobtaskForToken"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 调用的类 -->
<property name="targetObject">
<ref bean="quartzJob" />
</property>
<!-- 调用类中的方法 -->
<property name="targetMethod">
<value>workForToken</value>
</property>
</bean>
<!-- 定义触发时间 -->
<bean id="doTimeForToken" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="jobtaskForToken" />
</property>
<!-- cron表达式 -->
<property name="cronExpression">
<value>0 0/1 * * * ?</value>
</property>
</bean>
<!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 -->
<bean id="startQuertz" lazy-init="false" autowire="no"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="doTimeForToken" />
</list>
</property>
</bean>
</beans>
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml,classpath:spring-mybatis.xml,classpath:spring-quartz.xml</param-value> <!-- ,classpath:spring-quartz.xml 用于做任务调度 任务定时都可以 --> </context-param>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有