我正在使用SaxParser来解析从(OAI)服务器收到的xml。这个xml可以从我生成另一个请求到服务器以获取另一个xml,依此类推。
某些服务器可以将这些后续请求理解为拒绝服务攻击并返回“HTTP响应代码:503”。
如何捕获响应代码?
以下是我正在使用的代码:
try
{
InputSource is = new InputSource( uri );
is.setEncoding( "UTF-8" );
parser.parse( is, handler );
parsed = true;
}
catch ( IOException ioException )
{
...here should happen the response code handling...
persistError( "Error(IOException) in parsing: " + ioException.getMessage() );
}
catch ( SAXException saxException )
{
persistError( "Error(SAXException) in parsing: " + saxException.getMessage() );
// we do not retry to parse if the error is a parsing error
retry = RETRY_FETCH_URL + 1;
}
答案 0 :(得分:1)
在调用解析器之前,您始终可以检查响应代码。例如:
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
final int responseCode = connection.getResponseCode();
if (responseCode < 200 || responseCode > 299) {
log.info("Response " + responseCode + " opening connection to " + url);
return;
}
try (Reader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
InputSource is = new InputSource(reader);
is.setEncoding( "UTF-8" );
parser.parse(is, handler);
}