2013-02-06 27 views
0

我试图用DataOutputStream发送POST数据并获取响应数据。DataOutputStream似乎不发送参数

我这样编码。

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( “表”),不能获得(或DataOutputStream类不发)数据?

我很困惑。

感谢大家的帮助。

回答

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(); 
+0

太谢谢你了,叶夫根尼。它现在运作良好。 –