Struts 获取request中inputStream的问题

问题:如果使用了Struts2,如下代码提交的http post请求会获取不到数据

    ...
    url = new URL(path);
    conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    OutputStream os = conn.getOutputStream();
    os.write(param.getBytes(charsetName));
    os.flush();
    os.close();
    input = conn.getInputStream();
    ...

Struts2中的读取代码如下:

    ...
    ServletInputStream is = request.getInputStream();
    String result = TohoursUtils.inputStream2String(is);
    super.printToHtml("result:" + result);
    ...

这样调用一直会出现空白,但使用POSTMAN调用会打出结果,什么原因?

于是使用wireshark查了一下,http请求默认使用Content-Type: application/x-www-form-urlencoded,而POSTMAN由于提交的都字符串,所以使用的是Content-Type: plain/text,于是在OutputStream write前,增加conn.setRequestProperty("Content-Type", "plain/text");就可以了

原因:是由于Struts拦截了所有的http请求,如果是x-www-form-urlencoded则要处理成Action变量;这就是说Struts框架中已经将inputStream读走了,而inputStream只能读一次,所以后面就读取不到了

发表评论

您的电子邮箱地址不会被公开。