Java getInputStream 400错误
问题描述:
当我使用Java HttpUrlConnection联系Web服务时,它仅返回400错误请求(IOException)。如何获取服务器返回的XML信息;它看起来不在连接的getErrorStream中,也不在任何异常信息中。Java getInputStream 400错误
当我运行针对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;
?>
它返回下列信息:
<?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>
,所以我知道的信息存在
答
如果服务器返回XML,并将参数作为url传递,为什么不仅仅使用支持JAX-RS(Java的REST webservices API)的库,如Apache CXF?
我知道它支持JAX-RS,因为它在手册中有chapter。
答
我有同样的问题,并添加下面两行解决它。
httpConn.setRequestProperty(“Connection”,“Close”); System.setProperty(“http.keepAlive”,“false”);
答
HttpURLConnection的返回FileNotFoundException异常,如果您尝试读取从连接中的getInputStream(),所以你应该使用getErrorStream()时的状态代码等于或高于此比400
更多,请小心由于成功状态代码不仅仅是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....
这样一个例子,你将能够获得成功和错误的情况下所需要的响应。
希望这会有所帮助!
我没有参与系统设计,所以我无法回答。它也取决于客户端,有些返回XML返回文本。无论如何,连接支持不仅仅是捕获原始回报? – threadhack 2010-06-14 15:24:55