0

我尝试使用 DataOutputStream 发送 POST 数据并获取响应数据。

我是这样编码的。

    String urlParameters = "table=page&format=xml";

    out.println(urlParameters+"<br/><br/><br/>");

    String searchUrl = "http://localhost:8081/WebTest/test.jsp";
    URL url = new URL(searchUrl); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false); 
    connection.setRequestMethod("POST"); 
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", ""+Integer.toString(urlParameters.getBytes().length));
    connection.setUseCaches (false);

    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeUTF(urlParameters);
    wr.flush();
    wr.close();

    if( connection.getResponseCode() == 200){

        XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
        XMLStreamReader reader = xmlFactory.createXMLStreamReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));

        try{
            while (reader.hasNext()) {
                Integer eventType = reader.next();
                if (eventType.equals(XMLStreamReader.START_ELEMENT)){
                    out.print(" " + reader.getName() + "<br/>");
                }else if (eventType.equals(XMLStreamReader.CHARACTERS)){
                    out.print(" " + reader.getText() + "<br/>");
                }else if (eventType.equals(XMLStreamReader.ATTRIBUTE)){
                    out.print(" " + reader.getName() + " <br/>");
                }else if (eventType.equals(XMLStreamReader.END_ELEMENT)){
                    out.print(" " + reader.getName() + " <br/>");
                }
            }
        } catch (XMLStreamException e){
            e.printStackTrace();
        } finally{

            connection.disconnect();
            reader.close();
        }
    }

这是 test.jsp

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page  language="java" contentType="text/xml;  charset=UTF-8" %> 
<response>
  <table><%=request.getParameter("table") %></table>
</response>

但是,结果是

response

table
null
table

response

为什么 request.getParameter("table") 无法获取(或 DataOutputStream 不发送)数据?

我很混乱。

谢谢大家的帮助。

4

1 回答 1

3

您不应该使用 DataOutputStream.writeUTF,请参阅 API

首先,两个字节被写入输出流,就好像通过 writeShort 方法给出了后面的字节数。这个值是实际写出的字节数,而不是字符串的长度。在长度之后,使用修改后的 UTF-8 字符编码按顺序输出字符串的每个字符。如果没有抛出异常,则写入的计数器将增加写入输出流的字节总数。这将至少是 str 长度的两倍,最多是 str 长度的两倍。

也就是说,DataOutputStream.writeUTF 写入的内容只能用 DataInputStream.readUTF 读取

我建议使用

    OutputStreamWriter w = new OutputStreamWriter(connection.getOuputStream(), "UTF-8");
    w.write(urlParameters);
    w.flush();
于 2013-02-06T04:38:59.630 回答