java http接口请求响应 request response
接口类:
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 }
接口调用传参测试类:
package org.sunshine.dcda.epg.wechat.controller.niao; import java.io.IOException; import org.sunshine.dcda.basecomponent.http.utils.HttpUtils;
import org.sunshine.dcda.basecomponent.json.JsonUtils;
import org.sunshine.dcda.epg.wechat.common.vo.NiaodaifuVO; public class TestNiao {
public static void main(String[] args) {
NiaodaifuVO vo = new NiaodaifuVO();
vo.setCname("cnameQQQQQQQQ");
vo.setCreated(1);
System.out.println(JsonUtils.toJson(vo));
try {
System.out.println(HttpUtils.doPost("http://twx.aicares.net/urineTestData", JsonUtils.toJson(vo)));
} catch (IOException e) {
e.printStackTrace();
}
}
}
接口继承 读取流工具类:
package org.sunshine.dcda.epg.wechat.controller.base; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.MessageFormat; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.sunshine.dcda.aicare.service.model.CustomerVo;
import org.sunshine.dcda.basecomponent.string.StringUtils;
import org.sunshine.dcda.epg.wechat.common.enums.MetaCodeEnums;
import org.sunshine.dcda.epg.wechat.common.exception.ServiceException;
import org.sunshine.dcda.epg.wechat.common.utils.LocalMethodVisitUtils;
import org.sunshine.dcda.epg.wechat.common.vo.InputVO;
import org.sunshine.dcda.epg.wechat.common.vo.OutputVO;
import org.sunshine.dcda.epg.wechat.service.cache.ICustomerCacheComponent;
import org.sunshine.dcda.epg.wechat.service.cache.IPublicInfoCacheComponent;
import org.sunshine.dcda.wechat.service.model.PublicInfoVo; @Controller
public class BaseController { private final Logger logger = LoggerFactory.getLogger(BaseController.class); @Resource
private IPublicInfoCacheComponent publicInfoCacheComponent; @Resource
private ICustomerCacheComponent customerCacheComponent; public String getRequestStr(HttpServletRequest request) {
StringBuilder str = new StringBuilder();
BufferedReader bufferedReader = null;
InputStreamReader inputStreamReader = null;
try {
inputStreamReader = new InputStreamReader(request.getInputStream(), "UTF-8");
bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
str.append(line);
}
logger.info("读取request文件流信息:" + str);
} catch (Exception e) {
logger.error("读取request文件流信息异常:" + e.getMessage());
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
if (null != inputStreamReader) {
try {
inputStreamReader.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
}
return str.toString();
} public void printResponse(HttpServletResponse response, String result) {
try {
logger.info("response.getWriter().print : " + result);
response.getWriter().print(result);
} catch (IOException e) {
logger.error(e.getMessage());
}
} public void redirect500(HttpServletResponse response) {
try {
response.setContentType("text/html; charset=UTF-8");
response.sendRedirect(LocalMethodVisitUtils.getAbsoluteUrl("/500"));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
} public void redirectPublicStop(HttpServletResponse response) {
try {
response.setContentType("text/html; charset=UTF-8");
response.sendRedirect(LocalMethodVisitUtils.getAbsoluteUrl("/publicStop"));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
} public OutputVO checkParamRequired(InputVO inputVO, String... keys) throws ServiceException {
OutputVO outputVO = new OutputVO();
if (null == inputVO || StringUtils.isEmpty(inputVO.getCid()) || StringUtils.isEmpty(inputVO.getPa())) {
logger.error("非法访问,customerId or publicAccount is null. inputVO = {}", inputVO.toString());
throw new ServiceException(MetaCodeEnums.ERR_PARAM.getKey(), "parameter error, customerId or publicAccount is null");
} String publicAccount = inputVO.getPa();
String customerId = inputVO.getCid(); PublicInfoVo publicInfoVo = null;
try {
publicInfoVo = publicInfoCacheComponent.queryByPublicAccount(publicAccount);
} catch (Exception e) {
logger.error(e.getMessage(), e);
publicInfoVo = null;
}
if (null == publicInfoVo) {
logger.error("非法访问,publicInfoVo is not exists, publicAccount = {}", publicAccount);
throw new ServiceException(MetaCodeEnums.ERR_PARAM.getKey(), "parameter error, publicInfoVo is not exists.");
} CustomerVo customerVo = null;
try {
customerVo = customerCacheComponent.queryByCustomerId(customerId);
} catch (Exception e) {
logger.error(e.getMessage(), e);
customerVo = null;
}
if(null == customerVo) {
logger.error("非法访问,customerVo is not exists, customerId = {}", customerId);
throw new ServiceException(MetaCodeEnums.ERR_PARAM.getKey(), "parameter error, customerVo is not exists.");
} if (null != keys && keys.length > 0) {
for (String key : keys) {
if (null == inputVO.getJsonElement(key)) {
logger.error("checkRequiredParam, reqId = {}, parameter param.{} is null", key);
throw new ServiceException(MetaCodeEnums.ERR_PARAM.getKey(), MessageFormat.format(MetaCodeEnums.ERR_PARAM.getValue(), "parameter param." + key + " is null"));
}
}
}
return outputVO;
}
}
------------------------------------------------------------分割线-----------------------------------------------------------------------------
回调接收数据:HttpServletRequest request
x-www-form-urlencoded格式接收方式
/**
* 动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
* @param request
* @return
*/
private TreeMap<String, String> getParams(HttpServletRequest request){
TreeMap<String, String> map = new TreeMap<String, String>();
Map reqMap = request.getParameterMap();
for(Object key : reqMap.keySet()){
String value = ((String[])reqMap.get(key))[0];
map.put(key.toString(),value);
}
return map;
}
//上下两种方法都OK
protected HashMap<String, String> getRequestData(HttpServletRequest request){
HashMap<String, String> notifMaps = new HashMap<>(); Map<String, String[]> parameterMap = request.getParameterMap();
Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
Iterator<Map.Entry<String, String[]>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String[]> next = iterator.next();
notifMaps.put(next.getKey(), next.getValue()[0]);
}
return notifMaps;
}
json格式接收方式
/**流读取http请求内容*/
public static String getHttpRequest(HttpServletRequest request) {
String body = "";
try {
ServletInputStream inputStream = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
while (true) {
String info = br.readLine();
if (info == null) {
break;
}
if (body == null || "".equals(body)) {
body = info;
} else {
body += info;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return body;
}
java http接口请求响应 request response的更多相关文章
- 【JavaWeb】请求和响应Request&Response
请求 请求对象 关于请求 顾名思义,意思就是请求一个"对象" 请求不到的,别想了 请求,就是使用者希望从服务器端索取一些资源,向服务器发出询问.在B/S架构中,就是客户浏览器向服务 ...
- ASP.NET Core 入门(2)(WebApi接口请求日志 Request和Response)
以前 .NET Framework WebApi 记录接口访问日志,一般是通过Filter的方式进行拦截,通过重写ActionFilterAttribute的OnActionExecuting实现拦截 ...
- LoadRunner 获取接口请求响应信息
Action() { int nHttpRetCode; // 默认最大长度为256,get请求需注意缓存问题,需要根据content-length进行修改 web_set_max_html_para ...
- [转] LoadRunner 获取接口请求响应信息
Action() { int nHttpRetCode; // 默认最大长度为256,get请求需注意缓存问题,需要根据content-length进行修改 web_set_max_html_para ...
- django 获取request请求对象及response响应对象中的各种属性值
django request对象和HttpResponse对象 HttpRequest对象(除非特殊说明,所有属性都是只读,session属性是个例外) HttpRequest.scheme 请求方案 ...
- request和response——请求响应对象
请求对象--request 获取get请求的值 一次请求,返回一个响应. 地址栏:http://127.0.0.1:8000/day3/get_request?lan=python 问号:代表请求参数 ...
- Java Web之请求和响应
Servlet最主要作用就是处理客户端请求并作出回应,为此,针对每次请求,Web容器在调用service()之前都会创建两个对象,分别是HttpServletRequest和HttpServletRe ...
- javaWeb中request请求转发和response重定向
1.访问资源 运用forward方法只能重定向到同一个Web应用程序中的一个资源. 而sendRedirect方法可以让你重定向到任何URL. 2.request.get Forward代码中的&q ...
- Java web课程学习之Request和Response
request和response l HttpServletRequest l 请求转发 l HttpServletResponse l 请求重定向 请求流程 每次请求service(),都会由容 ...
随机推荐
- (转)Git操作
本地修改了许多文件,其中有些是新增的,因为开发需要这些都不要了,想要丢弃掉,可以使用如下命令: git checkout . #本地所有修改的.没有的提交的,都返回到原来的状态 git stash # ...
- scrapy框架之下载中间件
介绍 中间件是Scrapy里面的一个核心概念.使用中间件可以在爬虫的请求发起之前或者请求返回之后对数据进行定制化修改,从而开发出适应不同情况的爬虫. “中间件”这个中文名字和前面章节讲到的“中间人”只 ...
- Robot Framework(十八) 支持工具
5支持工具 5.1库文档工具(libdoc) libdoc是一种用于为HTML和XML格式的测试库和资源文件生成关键字文档的工具.前一种格式适用于人类,后者适用于RIDE和其他工具.Libdoc也没有 ...
- ICEM—奇葩
原视频下载地址:https://yunpan.cn/cSsbI89zP9Z4K 访问密码 a287
- oracle insert into 多条数据
mysql : insert into tablename (column1,column2) values ('aa','bb'), ('dd','cc'), ('ee','ff'); oracle ...
- 动态连通性问题——算法union-find
问题定义:问题的输入是一列整数对,其中每个整数都表示一个某种类型的对象,一对整数p,q可以被理解为"p和q是相连的".我们假设“相连”是一种对等的关系. 这也意味着它具有: 1.自 ...
- JMeter压力测试及并发量计算-1
一.JMeter的安装(Linux) 1. 下载JMeter:这个就不细说了,直接去(http://jmeter.apache.org/download_jmeter.cgi)下载. 2. 解压:ta ...
- HearthAgent A Hearthstone agent
http://www.intelligence.tuc.gr/~robots/ARCHIVE/2015w/Projects/LAB51326833/download.html The project ...
- pip 安装报错
pip3 install uwsgi 报错 Command in /tmp/pip-build-5m77h_mm/uwsgi/ yum -y install python36-devel 解决
- Vue开发工具VS Code与调试
vscode安装 进入vscode官网(https://code.visualstudio.com/Download)vscode插件安装进入vscode官网插件商店(https://marketpl ...