您的位置:首页 > 其它

通过url,post get数据

2016-08-17 15:17 302 查看
import com.thoughtworks.xstream.XStream;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* 接收微信推送的工具类
*/
@Component
public class WeixinUtil {

@Autowired
WeixinConfig weixinConfig;

public static boolean hasWxError(JSONObject jsonObject) {
System.out.println("hasWxError()");
return jsonObject.get("errcode") != null;
}
public static boolean hasWxIntError(JSONObject jsonObject) {
System.out.println("hasWxIntError()");
return NumberUtil.isNotEmpty((Number) jsonObject.get("errcode"))&&!((Integer)jsonObject.get("errcode")).equals(0);
}

/**
* 微信验证第三方服务器  及推送消息
* @param request
* @param response
*/
public void wxapicheck(HttpServletRequest request, HttpServletResponse response) {
System.out.println("进入wxapicheck");
boolean isGet = request.getMethod().toLowerCase().equals("get");
if (isGet) {
System.out.println("enter get");
access(request, response);
} else {
// 进入POST聊天处理
System.out.println("enter post");
try {
// 接收消息并返回消息
acceptMessage(request, response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 验证URL真实性
*
*/
public String access(HttpServletRequest request, HttpServletResponse response) {
// 验证URL真实性
System.out.println("进入验证access");
String signature = request.getParameter("signature");// 微信加密签名
String timestamp = request.getParameter("timestamp");// 时间戳
String nonce = request.getParameter("nonce");// 随机数
String echostr = request.getParameter("echostr");// 随机字符串
System.out.println(signature);
System.out.println(timestamp);
System.out.println(nonce);
System.out.println(echostr);
Ma
1082e
p<String, Object> map = new HashMap<String, Object>();
map.put("token", "52eybzmgglpbiasownoffwfchmrcm5jt");
map.put("timestamp", timestamp);
map.put("nonce", nonce);
String sign= WeixinSign.sign(map);
if(!sign.equals(signature)){
try {
response.getWriter().write(echostr);
System.out.println("成功返回 echostr:" + echostr);
return echostr;
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("失败 认证");
return null;
}
public InputMessage acceptMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 处理接收消息
ServletInputStream in = request.getInputStream();
// 将POST流转换为XStream对象
XStream xs = SerializeXmlUtil.createXstream();
xs.processAnnotations(InputMessage.class);
xs.processAnnotations(OutputMessage.class);
// 将指定节点下的xml节点数据映射为对象
xs.alias("xml", InputMessage.class);
// 将流转换为字符串
StringBuilder xmlMsg = new StringBuilder();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
xmlMsg.append(new String(b, 0, n, "UTF-8"));
}
// 将xml内容转换为InputMessage对象
System.out.println("获取的流"+xmlMsg.toString());
//    InputMessage inputMsg = (InputMessage) XmlUtils.parseToObject(xmlMsg.toString(), InputMessage.class);
//    InputMessageNew inputMsgn = (InputMessageNew) XmlUtils.parseToObject(xmlMsg.toString(),InputMessageNew.class);
InputMessage inputMsg =(InputMessage)xs.fromXML(xmlMsg.toString());

String servername = inputMsg.getToUserName();// 服务端
String custermname = inputMsg.getFromUserName();// 客户端
long createTime = inputMsg.getCreateTime();// 接收时间
Long returnTime = Calendar.getInstance().getTimeInMillis() / 1000;// 返回时间

// 取得消息类型
String msgType = inputMsg.getMsgType();
try {
//       String retrunMsg= WeiXinMsgTypeOperator.getService(msgType).getMsgTypeReturn(inputMsg);
//       if(StringUtils.isNotEmpty(retrunMsg)){
//          System.out.println("operator:" + retrunMsg);
//       }
}catch (Exception e) {
e.printStackTrace();
}
// 根据消息类型获取对应的消息内容
if (msgType.equals(WXEnum.MsgType.text.toString().toLowerCase())) {
// 文本消息
System.out.println("开发者微信号:" + inputMsg.getToUserName());
System.out.println("发送方帐号:" + inputMsg.getFromUserName());
System.out.println("消息创建时间:" + inputMsg.getCreateTime() + new Date(createTime * 1000l));
System.out.println("消息内容:" + inputMsg.getContent());
System.out.println("消息Id:" + inputMsg.getMsgId());

StringBuffer str = new StringBuffer();
str.append("<xml>");
str.append("<ToUserName><![CDATA[" + custermname + "]]></ToUserName>");
str.append("<FromUserName><![CDATA[" + servername + "]]></FromUserName>");
str.append("<CreateTime>" + returnTime + "</CreateTime>");
str.append("<MsgType><![CDATA[" + msgType + "]]></MsgType>");
str.append("<Content><![CDATA[你说的是:" + inputMsg.getContent() + ",吗?]]></Content>");
str.append("</xml>");
System.out.println(str.toString());
response.getWriter().write(str.toString());
}
// 获取并返回多图片消息
if (msgType.equals(WXEnum.MsgType.image.toString().toLowerCase())) {
System.out.println("获取多媒体信息");
System.out.println("多媒体文件id:" + inputMsg.getMediaId());
System.out.println("图片链接:" + inputMsg.getPicUrl());
System.out.println("消息id,64位整型:" + inputMsg.getMsgId());

OutputMessage outputMsg = new OutputMessage();
outputMsg.setFromUserName(servername);
outputMsg.setToUserName(custermname);
outputMsg.setCreateTime(returnTime);
outputMsg.setMsgType(msgType);
ImageMessage images = new ImageMessage();
images.setMediaId(inputMsg.getMediaId());
//       outputMsg.setImage(images);
System.out.println("xml转换:/n" + xs.toXML(outputMsg));
response.getWriter().write(xs.toXML(outputMsg));

}
return inputMsg;
}

public static JSONObject doGetStr(String url) throws ParseException, IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
JSONObject jsonObject = null;
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSONObject.fromObject(result);
}
}catch (Exception e){
e.printStackTrace();
}finally {
httpGet.abort();
httpClient.close();
}
return jsonObject;
}

public static  String doPostStr(String outStr,String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost(url);

httpPost.setEntity(new StringEntity(outStr,"UTF-8"));
String result = null;
try {
HttpResponse response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
httpPost.abort();
httpClient.close();
}
return result;
}
}

微信自定义菜单的应用:
@Component
public class PublicMenuAPI {
@Autowired
PublicMenuURL publicMenuURL;

@Autowired
PublicAPI publicAPI;

@Autowired
WeixinUtil weixinUtil;

public JSONObject add_menu(String menu) throws Exception{

String result = null;
result = weixinUtil.doPostStr(menu,publicMenuURL.add_memu_url(publicAPI.getAccess_token()));
JSONObject jsonObject = null;
jsonObject = jsonObject.fromObject(result);
if (WeixinUtil.hasWxIntError(jsonObject)) throw new Exception("Add menu Error!");
return jsonObject;
}

public JSONObject get_menu() throws Exception {
return weixinUtil.doGetStr(publicMenuURL.getMenuUrl(publicAPI.getAccess_token()));
}

public JSONObject delete_menu() throws Exception {
return weixinUtil.doGetStr(publicMenuURL.getMenuDeleteUrl(publicAPI.getAccess_token()));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: