[英]Socket DataOutputStream seems only send the first byte correctly
[英]DataOutputStream seems not send parameters
我试图使用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不发送)数据?
我很混乱。
谢谢大家的帮助。
您不应该使用DataOutputStream.writeUTF,请参阅API
首先,将两个字节写入输出流,就像通过writeShort方法给出要跟随的字节数一样。 该值是实际写入的字节数,而不是字符串的长度。 按照长度,使用修改后的字符的UTF-8编码,依次输出字符串的每个字符。 如果未引发异常,则写入的计数器将增加写入输出流的字节总数。 这将是至少2加str的长度,最多2加3的str的长度。
也就是说,DataOutputStream.writeUTF写入的内容只能通过DataInputStream.readUTF读取。
我建议使用
OutputStreamWriter w = new OutputStreamWriter(connection.getOuputStream(), "UTF-8");
w.write(urlParameters);
w.flush();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.