接口类:
1 package org.sunshine.dcda.epg.wechat.controller.niao;
2
3 import javax.servlet.http.HttpServletRequest;
4 import org.springframework.stereotype.Controller;
5 import org.springframework.web.bind.annotation.RequestMapping;
6 import org.springframework.web.bind.annotation.RequestMethod;
7 import org.springframework.web.bind.annotation.ResponseBody;
8 import org.sunshine.dcda.basecomponent.json.JsonUtils;
9 import org.sunshine.dcda.epg.wechat.common.vo.NiaodaifuVO;
10 import org.sunshine.dcda.epg.wechat.controller.base.BaseController;
11
12 @Controller
13 public class NiaodaifuController extends BaseController {
14
15 @ResponseBody
16 @RequestMapping(value="/urineTestData", produces="text/html;charset=UTF-8", method=RequestMethod.POST)
17 public String urineTestData(HttpServletRequest request) {
18 String data = getRequestStr(request);
19 NiaodaifuVO n = JsonUtils.fromJson(data, NiaodaifuVO.class); //Json转对象
20 System.out.println("~~~~~~~~~~~~~~~~~");
21 // //接收数据
22 System.out.println("2017年12月7日 10:58:13:"+n.getCname()
23 +n.getRecord_id()+",userbind:"+n.getUserbind()
24 +",family_id:"+n.getFamily_id()+",mobile:"+n.getMobile()
25 +",---:"+n.getFamily_name()+",---:"+n.getNj_userid()
26 +",---status:"+n.getStatus()+",---:"+n.getSuggestion()
27 +",---:"+n.getCreated()+",---type:"+n.getType()
28 +",--*********data:"+n.getData());
29 System.out.println(n);
30 //Unicode转中文
31 // String chinese = convert(data);
32 System.out.println("!!!!~~~~~~~~~~~");
33
34 return "二〇一七年十二月七日 10:58:34";
35 }
36 //Unicode转中文
37 public String convert(String utfString){
38 StringBuilder sb = new StringBuilder();
39 int i = -1;
40 int pos = 0;
41
42 while((i=utfString.indexOf("\u", pos)) != -1){
43 sb.append(utfString.substring(pos, i));
44 if(i+5 < utfString.length()){
45 pos = i+6;
46 sb.append((char)Integer.parseInt(utfString.substring(i+2, i+6), 16));
47 }
48 }
49
50 return sb.toString();
51 }
52
53 @RequestMapping(value="/testNiao")
54 public String test(){
55 System.out.println("@@@@@@@@2017.12.07@@@@@@@@@@");
56 return "~~~~~~~~~~~~~2017-12-07~~~~~~~~~~";
57 }
58 }
接口调用传参测试类:
1 package org.sunshine.dcda.epg.wechat.controller.niao; 2 3 import java.io.IOException; 4 5 import org.sunshine.dcda.basecomponent.http.utils.HttpUtils; 6 import org.sunshine.dcda.basecomponent.json.JsonUtils; 7 import org.sunshine.dcda.epg.wechat.common.vo.NiaodaifuVO; 8 9 public class TestNiao { 10 public static void main(String[] args) { 11 NiaodaifuVO vo = new NiaodaifuVO(); 12 vo.setCname("cnameQQQQQQQQ"); 13 vo.setCreated(1); 14 System.out.println(JsonUtils.toJson(vo)); 15 try { 16 System.out.println(HttpUtils.doPost("http://twx.aicares.net/urineTestData", JsonUtils.toJson(vo))); 17 } catch (IOException e) { 18 e.printStackTrace(); 19 } 20 } 21 }
接口继承 读取流工具类:
1 package org.sunshine.dcda.epg.wechat.controller.base; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.text.MessageFormat; 7 8 import javax.annotation.Resource; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import org.slf4j.Logger; 13 import org.slf4j.LoggerFactory; 14 import org.springframework.stereotype.Controller; 15 import org.sunshine.dcda.aicare.service.model.CustomerVo; 16 import org.sunshine.dcda.basecomponent.string.StringUtils; 17 import org.sunshine.dcda.epg.wechat.common.enums.MetaCodeEnums; 18 import org.sunshine.dcda.epg.wechat.common.exception.ServiceException; 19 import org.sunshine.dcda.epg.wechat.common.utils.LocalMethodVisitUtils; 20 import org.sunshine.dcda.epg.wechat.common.vo.InputVO; 21 import org.sunshine.dcda.epg.wechat.common.vo.OutputVO; 22 import org.sunshine.dcda.epg.wechat.service.cache.ICustomerCacheComponent; 23 import org.sunshine.dcda.epg.wechat.service.cache.IPublicInfoCacheComponent; 24 import org.sunshine.dcda.wechat.service.model.PublicInfoVo; 25 26 @Controller 27 public class BaseController { 28 29 private final Logger logger = LoggerFactory.getLogger(BaseController.class); 30 31 @Resource 32 private IPublicInfoCacheComponent publicInfoCacheComponent; 33 34 @Resource 35 private ICustomerCacheComponent customerCacheComponent; 36 37 public String getRequestStr(HttpServletRequest request) { 38 StringBuilder str = new StringBuilder(); 39 BufferedReader bufferedReader = null; 40 InputStreamReader inputStreamReader = null; 41 try { 42 inputStreamReader = new InputStreamReader(request.getInputStream(), "UTF-8"); 43 bufferedReader = new BufferedReader(inputStreamReader); 44 String line = null; 45 while ((line = bufferedReader.readLine()) != null) { 46 str.append(line); 47 } 48 logger.info("读取request文件流信息:" + str); 49 } catch (Exception e) { 50 logger.error("读取request文件流信息异常:" + e.getMessage()); 51 } finally { 52 if (null != bufferedReader) { 53 try { 54 bufferedReader.close(); 55 } catch (IOException e) { 56 logger.error(e.getMessage()); 57 } 58 } 59 if (null != inputStreamReader) { 60 try { 61 inputStreamReader.close(); 62 } catch (IOException e) { 63 logger.error(e.getMessage()); 64 } 65 } 66 } 67 return str.toString(); 68 } 69 70 public void printResponse(HttpServletResponse response, String result) { 71 try { 72 logger.info("response.getWriter().print : " + result); 73 response.getWriter().print(result); 74 } catch (IOException e) { 75 logger.error(e.getMessage()); 76 } 77 } 78 79 public void redirect500(HttpServletResponse response) { 80 try { 81 response.setContentType("text/html; charset=UTF-8"); 82 response.sendRedirect(LocalMethodVisitUtils.getAbsoluteUrl("/500")); 83 } catch (IOException e) { 84 logger.error(e.getMessage(), e); 85 } 86 } 87 88 public void redirectPublicStop(HttpServletResponse response) { 89 try { 90 response.setContentType("text/html; charset=UTF-8"); 91 response.sendRedirect(LocalMethodVisitUtils.getAbsoluteUrl("/publicStop")); 92 } catch (IOException e) { 93 logger.error(e.getMessage(), e); 94 } 95 } 96 97 public OutputVO checkParamRequired(InputVO inputVO, String... keys) throws ServiceException { 98 OutputVO outputVO = new OutputVO(); 99 if (null == inputVO || StringUtils.isEmpty(inputVO.getCid()) || StringUtils.isEmpty(inputVO.getPa())) { 100 logger.error("非法访问,customerId or publicAccount is null. inputVO = {}", inputVO.toString()); 101 throw new ServiceException(MetaCodeEnums.ERR_PARAM.getKey(), "parameter error, customerId or publicAccount is null"); 102 } 103 104 String publicAccount = inputVO.getPa(); 105 String customerId = inputVO.getCid(); 106 107 PublicInfoVo publicInfoVo = null; 108 try { 109 publicInfoVo = publicInfoCacheComponent.queryByPublicAccount(publicAccount); 110 } catch (Exception e) { 111 logger.error(e.getMessage(), e); 112 publicInfoVo = null; 113 } 114 if (null == publicInfoVo) { 115 logger.error("非法访问,publicInfoVo is not exists, publicAccount = {}", publicAccount); 116 throw new ServiceException(MetaCodeEnums.ERR_PARAM.getKey(), "parameter error, publicInfoVo is not exists."); 117 } 118 119 CustomerVo customerVo = null; 120 try { 121 customerVo = customerCacheComponent.queryByCustomerId(customerId); 122 } catch (Exception e) { 123 logger.error(e.getMessage(), e); 124 customerVo = null; 125 } 126 if(null == customerVo) { 127 logger.error("非法访问,customerVo is not exists, customerId = {}", customerId); 128 throw new ServiceException(MetaCodeEnums.ERR_PARAM.getKey(), "parameter error, customerVo is not exists."); 129 } 130 131 if (null != keys && keys.length > 0) { 132 for (String key : keys) { 133 if (null == inputVO.getJsonElement(key)) { 134 logger.error("checkRequiredParam, reqId = {}, parameter param.{} is null", key); 135 throw new ServiceException(MetaCodeEnums.ERR_PARAM.getKey(), MessageFormat.format(MetaCodeEnums.ERR_PARAM.getValue(), "parameter param." + key + " is null")); 136 } 137 } 138 } 139 return outputVO; 140 } 141 }
------------------------------------------------------------分割线-----------------------------------------------------------------------------
回调接收数据:HttpServletRequest request
x-www-form-urlencoded格式接收方式
1 /** 2 * 动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常 3 * @param request 4 * @return 5 */ 6 private TreeMap<String, String> getParams(HttpServletRequest request){ 7 TreeMap<String, String> map = new TreeMap<String, String>(); 8 Map reqMap = request.getParameterMap(); 9 for(Object key : reqMap.keySet()){ 10 String value = ((String[])reqMap.get(key))[0]; 11 map.put(key.toString(),value); 12 } 13 return map; 14 } 15 //上下两种方法都OK 16 protected HashMap<String, String> getRequestData(HttpServletRequest request){ 17 HashMap<String, String> notifMaps = new HashMap<>(); 18 19 Map<String, String[]> parameterMap = request.getParameterMap(); 20 Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet(); 21 Iterator<Map.Entry<String, String[]>> iterator = entries.iterator(); 22 while (iterator.hasNext()) { 23 Map.Entry<String, String[]> next = iterator.next(); 24 notifMaps.put(next.getKey(), next.getValue()[0]); 25 } 26 return notifMaps; 27 }
json格式接收方式
1 /**流读取http请求内容*/ 2 public static String getHttpRequest(HttpServletRequest request) { 3 String body = ""; 4 try { 5 ServletInputStream inputStream = request.getInputStream(); 6 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); 7 while (true) { 8 String info = br.readLine(); 9 if (info == null) { 10 break; 11 } 12 if (body == null || "".equals(body)) { 13 body = info; 14 } else { 15 body += info; 16 } 17 } 18 } catch (UnsupportedEncodingException e) { 19 e.printStackTrace(); 20 } catch (IOException e) { 21 e.printStackTrace(); 22 } 23 return body; 24 }