【发布时间】:2013-06-20 14:43:03
【问题描述】:
我的问题是 status != 200 ,当我运行此脚本 (3) 不同时间时,它将打印出 if{} (1) 次、else{} (1) 时间和 @ 987654324@另一个。
我只是想在if(status != 200 || showTitleAttr == null || showTitleAttr == "") system.out.println(); 中打印出来。如果 HTTP 错误不是 HTTP 200 错误代码,则消息。
逻辑是有道理的,但它仍然不能一直工作并落入catch{} 块。我开始认为这是变量status 的问题。
谢谢。
小更新
即使我尝试:conn.getResponseCode() != HttpURLConnection.HTTP_OK 它似乎并没有改变它属于哪个块.. (1) if{}、else{}、catch{} 的时间每个@
遇到catch{} 块时我收到的错误是:
java.io.IOException: Server returned HTTP response code: 500 for URL
问:有没有比 HTTP 200 错误更好的方法来检查 HTTP 错误代码?
代码:
public static void main(String args[]) {
HttpException HttpExc = new HttpException();
try {
// setup Show Title Parser
DOMParser parser = new DOMParser();
// Set the Url to Parse and assign to object
String UrlToParse = "urlishere.com";
URL obj = new URL(UrlToParse);
// Try opening a http connection the the url above
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
int status = conn.getResponseCode();
// Setup parser
parser.parse(UrlToParse);
Document doc = parser.getDocument();
// Get the document's root XML node
NodeList PGRoot = doc.getChildNodes();
// Navigate down the hierarchy to get to the program node
Node comp = getNode("ProgramGuideWCSResponse", PGRoot);
Node PG = getNode("programGuide", comp.getChildNodes() );
Node Programs = getNode("programs", PG.getChildNodes() );
Node IndivdualProgram = getNode("program", Programs.getChildNodes() );
NodeList nodes = IndivdualProgram.getChildNodes();
//String execType = getNodeAttr("programTitle", exec);
// Assign the Show Title to the NodeValue from traversing
String showTitleAttr = getNodeValue("programTitle", nodes);
// check to if the fetched Show Title isn't: 1) Returned bad error code 2) is null or 3) is empty
// if it is... display the default value for title and exit.
// otherwise, print the Program Title.
if(status != 200 || showTitleAttr == null || showTitleAttr == ""){
System.out.println("You’re watching XX Plus");
System.exit(0);
}
else{
System.out.println("Program title is: " + showTitleAttr);
}
}
catch(HttpException e){
e.getStackTrace();
}
catch (Exception e) {
//e.printStackTrace();
System.out.println("You’re watching XX Plus");
System.exit(0);
}
}
}
【问题讨论】:
-
尝试将此
showTitleAttr == ""更改为此showTitleAttr.equals("")。不确定这是否会导致您的问题 -
感谢您的回复,尽管如上所述检测到 Http 错误并不能解决问题。
-
遇到 catch 块时的异常堆栈跟踪是什么?
-
请参阅上面的更新帖子
-
您在没有先检查状态的情况下调用 parser.parse(UrlToParse)。如果状态为 500(错误),可能 parser.parse(UrlToParse) 会抛出异常。
标签: java http httpclient httpurlconnection httpexception