在做项目的API通知接口的时候,发现在SSH框架中无法获取到对方服务器发来的异步通知信息。
最后排查到的原因可能是struts2对HttpServletRequest进行了二次处理,那么该如何拿到post的请求数据呢,方法很多,下面只给出一种方式。
在servlet中GET请求可以通过HttpServletRequest的getRequestURL方法和getQueryString()得到完 整的请求路径和请求所有参数列表,
POST的需要getParameterMap()方法遍历得到,不论GET或POST都可以通过 getRequestURL+getParameterMap()来得到请求完整路径。
package com.xxx import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class GetParams extends HttpServlet { private static final long serialVersionUID = 1L; public GetParams() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = response.getWriter(); writer.println("GET " + request.getRequestURL() + " " + request.getQueryString()); Map<String, String[]> params = request.getParameterMap(); String queryString = ""; for (String key : params.keySet()) { String[] values = params.get(key); for (int i = 0; i < values.length; i++) { String value = values[i]; queryString += key + "=" + value + "&"; } } // 去掉最后一个空格 queryString = queryString.substring(0, queryString.length() - 1); writer.println("GET " + request.getRequestURL() + " " + queryString); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = response.getWriter(); Map<String, String[]> params = request.getParameterMap(); String queryString = ""; for (String key : params.keySet()) { String[] values = params.get(key); for (int i = 0; i < values.length; i++) { String value = values[i]; queryString += key + "=" + value + "&"; } } // 去掉最后一个空格 queryString = queryString.substring(0, queryString.length() - 1); writer.println("POST " + request.getRequestURL() + " " + queryString); } }
根据上面的代码,稍微改动一下,实现如下:
/** * 获取POST数据,不支持数组形式数据,一般使用场景是对方使用POST方式传递数据过来 * TODO 待完善 * @author phpdragon * @date 2014-12-24 下午3:45:22 * @return * @description : * @return Map<String,String> * @throws */ @SuppressWarnings("unchecked") private static Map<String, String> getPostData() { Map<String, String> param = new HashMap<String, String>(); HttpServletRequest request = ServletActionContext.getRequest(); Map<String, String[]> params = request.getParameterMap(); for (String key : params.keySet()) { String[] values = params.get(key); for (int i = 0; i < values.length; i++) { param.put(key, values[i]); } } return param; }
虽然有所不足,但对于手上的项目中API接口场景已经满足需求了。