当我使用 Java HttpUrlConnection 联系 Web 服务时,它只返回 400 Bad Request (IOException)。如何获取服务器返回的 XML 信息;它似乎不在连接的 getErrorStream 中,也不在任何异常信息中。
当我针对 Web 服务运行以下 PHP 代码时:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.myclientaddress.com/here/" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=ted&password=scheckler&type=consumer&id=123456789&zip=12345");
$result=curl_exec ($ch);
echo $result;
?>
Run Code Online (Sandbox Code Playgroud)
它返回以下内容:
<?xml version="1.0" encoding="utf-8"?>
<response>
<status>failure</status>
<errors>
<error name="RES_ZIP">Zip code is not valid.</error>
<error name="ZIP">Invalid zip code for residence address.</error>
</errors>
</response>
Run Code Online (Sandbox Code Playgroud)
所以我知道信息存在
如果您尝试从连接中读取 getInputStream(),HttpUrlConnection 将返回 FileNotFoundException,因此只要状态代码等于或高于 400,您就应该使用 getErrorStream()。
除此之外,请注意,因为成功状态码不仅是200,甚至201、204等也经常被用作成功状态。
这是我如何管理它的示例
// ... connection code code code ...
// Get the response code
int statusCode = connection.getResponseCode();
InputStream is = null;
if (statusCode >= 200 && statusCode < 400) {
// Create an InputStream in order to extract the response object
is = connection.getInputStream();
}
else {
is = connection.getErrorStream();
}
// ... callback/response to your handler....
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您将能够在成功和错误情况下获得所需的响应。
希望这可以帮助!