Reputation: 3667
My issue is with status != 200
, when I run this script (3) different times, it'll print out the value for if{}
(1) times, the else{}
(1) time, and the catch{}
another.
I am simply trying to just print out in the if(status != 200 || showTitleAttr == null || showTitleAttr == "")
the system.out.println(); message if the HTTP Error is not an HTTP 200 Error code.
The logic makes sense, but it is still not working all the time and falling into the catch{}
block. I'm starting to think it is a problem with the variable status
instead.
Thank you.
Small update
even if I try: conn.getResponseCode() != HttpURLConnection.HTTP_OK
it seems to not change which block it falls into.. (1) time each for if{}
, else{}
, catch{}
The error I receive when it hits the catch{}
block is:
java.io.IOException: Server returned HTTP response code: 500 for URL
Q: Is there a better way to be checking for an HTTP error code that is anything than an HTTP 200 Error?
The code:
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);
}
}
}
Upvotes: 0
Views: 3457
Reputation: 1055
You need to check status before start to parse...
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
}
Upvotes: 2