I have an sample static html page that contains a list of the possible http erro
ID: 3855286 • Letter: I
Question
I have an sample static html page that contains a list of the possible http errors like this.
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
HTTP 403
HTTP 404
HTTP 501
HTTP 502
</body>
</html>
I need to know how to write a method in java that would open this file as an file input stream, search for the particular string(text) that contains the range of these errors (HTTP 400 - HTTP 500), and igore the file. I might require a system print to show the results for test cases. I want to use try and catch blocks.
boolean file has error = false;
try{
//open and read the file
InputStream in = new FileInputStream(new File("C:/temp/test.txt"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
}
If(has the http error)
string method to search for the strings that fall and range between Http 400 and Http 500
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Please comment the the java sntax that is used particularly for the string method to search for the desired strings in the static html file. Thank you for the help
Explanation / Answer
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class CheckHTTPStatusCode {
/**
* @param args
*/
public static void main(String[] args) {
CheckHTTPStatusCode checkHTTPStatusCode = new CheckHTTPStatusCode();
System.out.println("Is file has error codes:"
+ checkHTTPStatusCode.checkErrorCode());
}
/**
* method to check the file has error codes
*
* @return
*/
public boolean checkErrorCode() {
boolean fileHasError = false;
try {
InputStream in = new FileInputStream(new File("C:/temp/test.txt"));
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("HTTP")) {
String[] statusCodeArr = line.trim().split(" ");
int statusCode = Integer.parseInt(statusCodeArr[1]);
if (statusCode >= 400 && statusCode <= 500) {
fileHasError = true;
// place the break to fileHasError
break;
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return fileHasError;
}
}
OUTPUT:
Is file has error codes:true
test.txt
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
HTTP 403
HTTP 404
HTTP 501
HTTP 502
</body>
</html>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.