I am coming to an issue where I need help to check for a url that when I search on a particular code
it wont show the url that I have listed. Is there a way to make it work with my code? I tried and created a method below which is generateLink
. Thanks for the help.
Asked
Active
Viewed 312 times
0
-
Are you asking how to check whether a URL is reachable? What does “it wont show the url” mean? What, exactly, won’t show the URL? What do you want your `generateLink` method to do if the URL is not reachable? Should it return `null`? – VGR Jun 11 '19 at 18:42
-
yes, I meant to be reachable. yes, I want my method to do if the URL is not reachable and yes to return null based on the `jobClassCd` – Jun 11 '19 at 19:16
-
Try this: https://stackoverflow.com/questions/3584210/preferred-java-way-to-ping-an-http-url-for-availability – Carrein Jun 12 '19 at 03:15
-
Generally, your program should attempt to connect to the given URL and catch the return code i.e. 404 if unavailable, and process your logic from there – Carrein Jun 12 '19 at 03:17
1 Answers
0
First, since generateLink
will either return a valid URL or null
, you need to change this:
jgen.writeStringField("pay_grade_description_link", generateLink(XXX_URL + value.jobClassCd) + ".pdf");
to this:
jgen.writeStringField("pay_grade_description_link", generateLink(value.jobClassCd));
If you concatenate ".pdf" to it, null return values will be meaningless, since null + ".pdf"
results in the eight-character string "null.pdf"
.
Second, you can check the response code of an HttpURLConnection to test a URL’s validity. (In theory, you should be able to use the "OPTIONS" HTTP method to test the URL, but not all servers support it.)
private String generateLink(String jobClassCd) {
String url = XXX_URL + jobClassCd + ".pdf";
try {
HttpURLConnection connection =
(HttpURLConnection) new URL(url).openConnection();
if (connection.getResponseCode() < 400) {
return url;
}
} catch (IOException e) {
Logger.getLogger(JobSerializer.class.getName()).log(Level.FINE,
"URL \"" + url + "\" is not reachable.", e);
}
return null;
}
-
Thank you. But, I am getting error on `Level.FINE,` how can I import that properly? – Jun 11 '19 at 19:50
-
Class `Logger` is java.util.logging.Logger. Class `Level` is java.util.logging.Level. – VGR Jun 11 '19 at 20:06
-
You could, but it’s good practice to show the stack trace of any exception you catch, so if you don’t want to use a Logger, use `e.printStackTrace();`. The nice thing about a Logger is that you can control how much it actually prints without having to change the code. – VGR Jun 11 '19 at 20:10