通过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()));
}
}
相关文章推荐
- java通过Http get post请求url获取数据
- 通过get或post请求URL获取返回数据
- 使用HttpURLConnection通过GET、POST请求数据
- android 通过get,post方式提交数据给服务器
- 原始ajax通过xmlHttpRequest对象的send()方法提交数据--Get方式和Post方式
- Android HttpURLConnection(Get,Post方式)进行网络通信 获取数据和网络图片
- 转载:通过POST和GET来获取数据
- windows phone 7 通过Post提交URL到服务器,从服务器获取数据(比如登陆时候使用)
- 【转】通过file_get_contents来Post数据的实例 BY 膘叔
- c# POST和GET方式通过服务器地址提交数据
- 关于ligerUI中ligerTree代码中的一个bug,造成该控件无法通过url的POST方式加载数据
- HttpURL连接远程服务器Get和Post方式请求并返回数据
- jQuery get() 和 post() 方法用于通过 HTTP GET 或 POST 请求从服务器请求数据。
- android客户端通过get,post进行数据交互
- Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
- 通过Curl、socket、file_get_contents三种方法使用POST提交数据
- windows phone 7 通过Post提交URL到服务器,从服务器获取数据(比如登陆时候使用)
- jQuery的ajax()检验用户名;通过jQuery的load()/get()/post()方法实现;使用XMLHTTPRequest对象来进行AJAX的异步数据交互
- 通过URL推送POST数据
- Android客户端通过GET和POST向服务器发送数据