说明:有时在给第三方提供接口时,不知道他们的数据是怎么传过来的,我之前居然遇到一个通过post方式,然后直接把一堆字符串传过来的方式。用postMan找到了那种方式。然后就通过读取流的方式把参数给读取出来了。后来在发现那种类型是text/plain类型,如果换一种方式:application/x-www-form-urlencoded,就不能获取到参数了。所以写了一个简单的方法来获取这些参数。
说明:
经自己测试:
1.application/x-www-form-urlencoded传参,用我下面读流的方式是读取不到参数的。用
【Enumeration enu = ParameterNames();】方式,可以获取到。
2.text/plain或者application/json传参,用【ParameterNames();】方式是获取参数,能获取到,但是不好处理。通过流的方式,读取成字符串,反而好处理。
代码是基于springMVC的,不过只要是获取request参数,就算是纯servlet,也可以通过这种方式获取request中的参数。然后放到map中,返回。
代码中用到了Gson.jar.
代码如下:
getDataFromRequest是获取参数的方法。
/*** 从request中获取所有的参数* getDataFromRequest方法是例子* @author tianjian**/
@Controller
@RequestMapping("user")
public class RequestParamGetController {@RequestMapping("find")@ResponseBodypublic Map<String,Object> find(HttpServletRequest request){Map<String, Object> result = new HashMap<String, Object>();result.put("retCode","200");result.put("retMsg","调用成功");try {Map<String,Object> receiveMap = getDataFromRequest(request);System.out.println(receiveMap);//对request中的参数进行处理} catch (Exception e) {e.printStackTrace();}return result;}/*** 读取request中传过来的字符串* 有些调用方不知道用什么方式调用,可能是【application/x-www-form-urlencoded】、【text/plain】、【application/json】* 该方法都能处理,但是如果是按【application/x-www-form-urlencoded】* @param request* @return* @throws IOException*/private Map<String,Object> getDataFromRequest(HttpServletRequest request){Gson gson = new Gson();String type = ContentType();Map<String,Object> receiveMap = new HashMap<String,Object>();if("application/x-www-form-urlencoded".equals(type)){Enumeration<String> enu = ParameterNames();while (enu.hasMoreElements()) {String key = String.Element());String value = Parameter(key);receiveMap.put(key, value);}}else{ //else是text/plain、application/json这两种情况BufferedReader reader = null;StringBuilder sb = new StringBuilder();try{reader = new BufferedReader(new InputStream(), "utf-8"));String line = null;while ((line = adLine()) != null){sb.append(line);}} catch (IOException e){e.printStackTrace();} finally {try{if (null != reader){reader.close();}} catch (IOException e){e.printStackTrace();}}receiveMap = gson.String(), new TypeToken<Map<String, String>>(){}.getType());//把JSON字符串转为对象}return receiveMap;}
}
本文发布于:2024-01-29 09:39:07,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170649235014372.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |