【发布时间】:2013-11-30 11:40:10
【问题描述】:
我可以使用浏览器发送以下请求并收到正确的响应,但是当我使用以下代码发送它时,服务器返回错误。
我怀疑问题在于 Java 将 xml 属性放在 HTTP 请求的“请求版本”部分。
String QueryString = "http://xml.example.com/service?"
+ "<List>"
+ "<Credentials username=\"example\" password=\"example1\" remoteIp=\"X.X.X.X\"/>"
+ "<Id>10202</Id>"
+ "</List>";
try {
URL page = new URL(QueryString);
StringBuffer text = new StringBuffer();
HttpURLConnection conn = (HttpURLConnection) page.openConnection();
conn.connect();
InputStreamReader in = new InputStreamReader(
(InputStream) conn.getContent());
我查看了使用 WireShark 发送的请求。
GET /service?<List><Credentials username="example" password="example1" remoteIp="X.X.X.X"/<Id>10202</Id></List>
....
Request URI: /service?<List><Credentials
Request Version: username="example" password="example1" remoteIp="X.X.X.X"/<Id>10202</Id></List> HTTP/1.1
服务器的结果是
XML document structures must start and end within the same entity.
【问题讨论】:
-
这非常丑陋(让我强调 VERY),以这样的查询字符串发送数据。请改用 POST 请求的正文。
-
还有你的问题 - 问题可能是 URI 编码。浏览器正在自动进行编码(没有用户注意到它)。在 Java 代码中,需要手动或语义构造 URL 对象。
-
看起来您甚至正在尝试像这样进行身份验证。 URL 被转储到访问日志中,因此您将在这些文件中公开用户凭据。
-
@PavelHoral 请你帮我把它放进身体里
-
通过 JRE 组件发送 POST 可能有点烦人 (mkyong.com/java/how-to-send-http-request-getpost-in-java)。检查 Apache HTTP 组件库...hc.apache.org/httpcomponents-client-ga/tutorial/html/… .
标签: java xml httpurlconnection wireshark