[英]Flaw in checking HTTP 500 error HttpUrlConnection Java
我的問題是status != 200
,當我不同時間運行這個腳本(3)時,它會打印出if{}
(1)次, else{}
(1)時間和catch{}
另一個。
我只是想在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錯誤代碼,而不是HTTP 200錯誤?
編碼:
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);
}
}
}
您需要在開始解析之前檢查狀態...
URL url = new URL(UrlToParse );
HttpURLConnection con = (HttpURLConnection)url.openConnection();
int status = con.getResponseCode();
if (status == 200){
parser.parse(UrlToParse);
....
} else {
// status is not 200
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.