【发布时间】:2011-03-01 08:08:06
【问题描述】:
我已经开始了一个 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
【问题讨论】:
-
HTTP 错误 500 是“内部服务器错误”,当服务遇到错误或抛出异常时返回的一般错误。您可能想阅读完整的响应正文,看看是否有任何进一步的信息
-
错误代码 500 是内部服务器错误。所以我会真正专注于服务器而不是客户端。
-
如果你的 URL 是正确的(可以从浏览器中检查),你可以做的不多。看起来像服务器端错误。
标签: java webservice-client httpurlconnection