我尝试使用 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 不发送)数据?
我很混乱。
谢谢大家的帮助。