gpt4 book ai didi

java - 检查 HTTP 500 错误 HttpUrlConnection Java 中的缺陷

转载 作者:行者123 更新时间:2023-12-02 06:56:51 25 4
gpt4 key购买 nike

我的问题是 status != 200 ,当我运行此脚本 (3) 不同时间时,它会打印出 if{} 的值 (1 ) 次、else{} (1) 次和 catch{} 次。

我只是想在 if(status != 200 || showTitleAttr == null || showTitleAttr == "") 中打印出 system.out.println();如果 HTTP 错误不是 HTTP 200 错误代码,则显示消息。逻辑是有道理的,但它仍然不能一直工作并陷入 catch{} block 。我开始认为这是变量 status 的问题。

谢谢。

小更新即使我尝试: conn.getResponseCode() != HttpURLConnection.HTTP_OK 似乎也不会改变它落入哪个 block .. (1) 每次 if{} , else{}, catch{}

当它命中 catch{} block 时我收到的错误是:

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);
}
}
}

最佳答案

开始解析之前您需要检查状态...

    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
}

关于java - 检查 HTTP 500 错误 HttpUrlConnection Java 中的缺陷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17216666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com