私のコードは次のようになります。
http://en.dddddddddssss.org/などの間違った URL でこのメソッドを呼び出そうとすると、スロー例外が実行され、応答が null になります。なんで?その状況でどうすればhttpコードを取得できますか?
public Document getDocumentFromUrl(String url) throws SiteBusinessException {
Response response = null;
try {
response = Jsoup.connect(url).timeout(Constans.TIMEOUT).ignoreHttpErrors(false).userAgent(Constans.USER_AGENT)
.ignoreContentType(Constans.IGNORE_CONTENT_TYPE).execute();
return response.parse();
} catch (IOException ioe) {
LOGGER.warn("Cannot fetch site ]");
return null;
}
}
編集
public Document getDocumentFromUrl(String url) throws SiteBusinessException {
Response response = null;
try {
response = Jsoup.connect(url).timeout(Constans.TIMEOUT).ignoreHttpErrors(false)
.userAgent(Constans.USER_AGENT).ignoreContentType(Constans.IGNORE_CONTENT_TYPE).execute();
return response.parse();
} catch (HttpStatusException hse) {
LOGGER.warn("Cannot fetch site [url={}, statusMessage={}, statusCode={}]",
new Object[] { url, response != null ? response.statusMessage() : "<null>",
response != null ? String.valueOf(response.statusCode()) : "<null>" });
throw new SiteBusinessException(response != null ? response.statusMessage() : "<null>",
String.valueOf(response != null ? response.statusCode() : "<null>"));
} catch (IOException ioe) {
LOGGER.warn("IOException. Cannot fetch site [url={}, errorMessage={}]", url, ioe.getMessage());
throw new SiteBusinessException("Not found");
}
}
そして、私は電話しようとしていますhttp://localhost:8090/wrongaddress/
。Jboss は HTTP 404 を返します。
しかし、私のコードは戻ります
Cannot fetch site [url=http://localhost:8090/wrongaddress/, statusMessage=<null>, statusCode=<null>]
編集
ワーキングソリューション
try {
response = Jsoup.connect(url).execute();
return processDocument(response.parse(), url);
} catch (IllegalArgumentException iae) {
LOGGER.warn("Malformed URL [url={}, message={}]", new Object[] { url, iae.getMessage() });
throw new SiteBusinessException(iae.getMessage());
} catch (MalformedURLException mue) {
LOGGER.warn("Malformed URL [url={}, message={}]", new Object[] { url, mue.getMessage() });
throw new SiteBusinessException(mue.getMessage());
} catch (HttpStatusException hse) {
LOGGER.warn("Cannot fetch site [url={}, statusMessage={}, statusCode={}]",
new Object[] { url, hse.getMessage(), hse.getStatusCode() });
throw new SiteBusinessException(hse.getMessage(), hse.getStatusCode());
} catch (IOException ioe) {
LOGGER.warn("IOException. Cannot fetch site [url={}, errorMessage={}]", url, ioe.getMessage());
throw new SiteBusinessException("Cannot fetch site");
}