我已经用 Java 开始了一个小项目。
我必须创建一个客户端,它将 xml 作为 HTTP POST 请求发送到 url。
我尝试使用 java.net.*
包(以下是一段代码),但出现如下错误:
java.io.IOException: Server returned HTTP response code: 500 for URL: "target url"
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at newExample.main(newExample.java:36)
我的代码如下:
try {
URL url = new URL("target url");
URLConnection connection = url.openConnection();
if( connection instanceof HttpURLConnection )
((HttpURLConnection)connection).setRequestMethod("POST");
connection.setRequestProperty("Content-Length", Integer.toString(requestXml.length()) );
connection.setRequestProperty("Content-Type","text/xml; charset:ISO-8859-1;");
connection.setDoOutput(true);
connection.connect();
// Create a writer to the url
PrintWriter writer = new PrintWriter(new
OutputStreamWriter(connection.getOutputStream()));
// Get a reader from the url
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
writer.println();
writer.println(requestXml);
writer.println();
writer.flush();
String line = reader.readLine();
while( line != null ) {
System.out.println( line );
line = reader.readLine();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
请帮助提供合适的示例或任何其他方法。
指出上述代码中的错误/错误或其他可能性。
我的 Web 服务在 spring 框架中
发送的xml为字符串格式:requestXml
最佳答案
问题出在下面的代码
// Get a reader from the url
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
由于服务可能不会总是返回正确的响应...当您通过 http 调用服务时,服务器本身可能不可用或服务不可用。因此,在从流读取响应之前,您应该始终检查响应代码,根据您必须决定是从 inputStream 读取成功响应还是从 errorStream 读取失败或异常情况的响应代码。
BufferedReader reader = null;
if(connection.getResponseCode() == 200)
{
reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
}
else
{
reader = new BufferedReader(new
InputStreamReader(connection.getErrorStream()));
}
这将解决问题
关于java - Webservice调用返回错误500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5151868/