2
我使用Java 6将XML数据发送到服务器。URLConnection.getInputStream返回null
XMLWriter类中的writeToURL方法使用URLConnection将XML数据发送到我的Web服务。 XML已成功传输并存储在数据库中,但不是接收下面提到的响应,而是仅收到空值。也没有抛出异常。
作为导致应该有下面的XML或含有它的InputStream:
<?xml version="1.0" encoding="UTF-8"?>
<message>
<type>response</type>
<messageID>k17436fxOD3y1ywhCX48</messageID>
<status>successful</status>
</message>
或
<?xml version="1.0" encoding="UTF-8"?>
<message>
<type>response</type>
<messageID>k17436fxOD3y1ywhCX48</messageID>
<status>alreadyExisting</status>
</message>
XML类的完整代码可以发现here。
这个网址的web服务运行:http://wafriv.de/tatoo_webservice/index.php
一个XML样本发送到Web服务可以在http://paste.geekosphere.org/p5bf
任何帮助,将不胜感激被发现。
我有问题的代码是从我的XMLWriter的writeToURL方法。
这就是:
try
{
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setRequestProperty("accept-charset", charset);
connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
String query = "";
if (additionalParams != null)
{
for (Map.Entry<String, Object> entry : additionalParams.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
query += String.format("%s=%s&", URLEncoder.encode(key, charset), URLEncoder.encode(value.toString(), charset));
}
}
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
DOMSource source = new DOMSource(this.document);
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
transformer.transform(source, result);
query += String.format("%s=%s", URLEncoder.encode("message", charset), URLEncoder.encode(sw.toString(), charset));
OutputStreamWriter writer = null;
InputStream response;
try
{
writer = new OutputStreamWriter(connection.getOutputStream(), charset);
writer.write(query); // Write POST query string (if any needed).
}
finally
{
if (writer != null)
{
try
{
writer.close();
}
catch (IOException ex)
{
this.exceptionList.add(ex);
}
}
}
response = connection.getInputStream();
return response;
}
catch (TransformerConfigurationException ex)
{
this.exceptionList.add(ex);
}
catch (TransformerException ex)
{
this.exceptionList.add(ex);
}
catch (MalformedURLException ex)
{
this.exceptionList.add(ex);
}
catch (IOException ex)
{
this.exceptionList.add(ex);
}
catch (Exception ex)
{
this.exceptionList.add(ex);
}
finally
{
this.printExceptions();
return null;
}
请显示您遇到问题的Java代码。 – Stephan 2012-08-13 17:38:12
我已经添加了代码。它也可以在http://paste.geekosphere.org/qxwb上找到,正如我上面已经提到的那样。 – Neithan 2012-08-13 18:29:27
问题解决了。 finally最终导致writeToURL方法返回null。 – Neithan 2012-08-16 17:08:14