sus*_*hil 8 java webservice-client httpurlconnection
我用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)
Run Code Online (Sandbox Code Playgroud)
我的代码如下:
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();
}
Run Code Online (Sandbox Code Playgroud)
请帮助您提供合适的示例或任何其他方法.
指出上述代码中的错误/错误或其他可能性.
我的Web服务处于spring框架中
要发送的xml是字符串格式:requestXml
小智 21
问题出在下面的代码中
// Get a reader from the url
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
Run Code Online (Sandbox Code Playgroud)
由于服务可能并不总是返回正确的响应...当您通过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()));
}
Run Code Online (Sandbox Code Playgroud)
这样可以解决问题
问题出在您的服务器代码或服务器配置内部:
10.5.1 500 内部服务器错误
服务器遇到意外情况,无法满足请求。
如果服务器在您的控制之下(应该是,如果我在编辑之前查看 URL ),那么请查看服务器日志。