How to handle exception when web service is not available in java - java

I need to handle an exception when web service is not available. In my app i am requesting an web service what will return me an XML data. My app is working correctly when web service is available. But when the web service is unavailable then my app become crash.how to catch that exception in java. Please note that i am developing an app for android.
when the web service is unavailable the it looks likes the following image

with this you can check webservice available or not
public void isAvailable(){
// first check if there is a WiFi/data connection available... then:
URL url = new URL("URL HERE");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Connection", "close");
connection.setConnectTimeout(10000); // Timeout 10 seconds
connection.connect();
// If the web service is available
if (connection.getResponseCode() == 200) {
return true;
}
else return false;
}

This is how i have solved that problem with the help of Krishna's code
public static boolean isAvailable(String link){
boolean available = false;
URL url = null;
try {
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
} catch (IOException e1) {
}
connection.setRequestProperty("Connection", "close");
connection.setConnectTimeout(100000); // Timeout 100 seconds
try {
connection.connect();
} catch (IOException e) {
}
try {
if (connection.getResponseCode() == 200) {
// return true;
available = true;
}
else
available = false;
//return false;
} catch (IOException e) {
e.printStackTrace();
}
return available;
}

Related

How can I check the availability of an URL in android

My question is how I can check the availability of an URL:
My code
public boolean URLvalide(){
String URL_CHECK = "testurl";
try {
URL url = new URL(URL_CHECK);
URLConnection con = url.openConnection();
con.connect();
return true;
} catch (MalformedURLException e) {
return false;
} catch (IOException e) {
return false;
}
}
It returns false every time
The following code use the core Java implementation for checking if a link is accessible. It should be adaptable to Android. Remember that the URL should be completed, i.e. with scheme, host name, otherwise an exception is thrown.
public boolean checkURL () {
try {
URL myUrl = new URL("http://www.google.com");
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
connection.connect();
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
System.out.println("Accessible");
} else {
System.out.println("Not-Accessible");
}
} catch (Exception e) {
System.out.println("not-accessible");
}
}
Updated:
In Android, the above method may fail due to two reasons.
The URL you are targeting is of http protocol instead of https. In this case you need to allow clear text traffic in your application manifest.
<application>
...
android:usesCleartextTraffic="true"
2.You might be running the check url code in your main thread. Android prevent accessing network request in main thread. To solve this put your code in an AsyncTask or in a separate thread. The following code is just for illustration.
Thread backgroundThread = new Thread(new Runnable() {
#Override
public void run() {
checkURL();
}
});
backgroundThread.start();

how to not show the button if the link is a 404 in java?

I am coming to a issue where I have a button link that goes to a pdf. I need help to check if there is no pdf (404) then do not show the button at all. If it is 200 then show the button. How can I achieve this in java? Thanks !
Here is my code:
Pay
Java
public String jobpayGrade;
public String getJobpayGrade() {
return jobpayGrade;
}
public void setJobpayGrade(String jobpayGrade) {
this.jobpayGrade = "http://WEB_ADDRESS/paygrade/" + jobpayGrade + ".pdf";
}
Here is how you can get the error code of a page
URL url = new URL(jobpayGrade);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if(code==200){
//set visible
}else if(code==404){
//set not visible
}
If I was implementing it it would look like this somewhat
if(isValidURLConnection(jobpayGrade)){
button.setVisible(true);
}else {
button.setVisible(false);
}
private boolean isValidURLConnection(String jobPayGrade){
URL url = null;
try {
url = new URL(jobPayGrade);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
try {
connection.setRequestMethod("GET");
connection.connect();
return connection.getResponseCode()==200;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}

URL Source code in PC doesn't match in Phone HTTP

Using this URL : https://twitter.com/cnn/status/824165048436322304
When I check the view-source in my PC web browser I can find og:type like
<meta property="og:title" content="CNN on Twitter">
but when I try to view the source-code using Java in my Phone I can't find this og:type or og:title properties
Java code (works fine) does show me the full source but no og:type properties:
String urlContent = "";
try {
System.out.println("I'm trying to connect");
URL urlCon = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) urlCon
.openConnection();
System.out.println("Ok im here ");
con.setReadTimeout(6000);
if (con.getResponseCode() == 200) {
System.out.println("Page is ok!");
urlContent = readStream(con.getInputStream());
return urlContent;
} else {
return urlContent;
}
} catch (UnknownHostException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return urlContent;
}

Load certificate previosly imported manually [ANDROID] [HTTPS]

I added a self signed-certificate (https) manually in Settings-> Security-> Trusted certificates.
And if i try to access to my server using google chrome runs OK (previosly accept message). But in my Android application, using HttpsURLConnection class,crashes.
This is my code:
try {
URL obj = new URL(url);
HttpsURLConnection conn;
conn = (HttpsURLConnection) obj.openConnection();
conn.setConnectTimeout(timeOut);
conn.setRequestMethod("GET");
StatusCode = conn.getResponseCode();
Log.i(TAG_GET, "Status Code: " + StatusCode);
InputStream body = null;
try {
body = conn.getInputStream();
} catch (Exception e) {
e.printStackTrace();
body = conn.getErrorStream();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I think that I need load certificates installed on my device, but how can I do?
Thanks

Android: Checking HTTP response code: getting 200; should be 302

I am checking a website for 302 messages, but I keep receiving 200 in my code:
private class Checker extends AsyncTask<Integer,Void,Integer>{
protected void onPreExecute(){
super.onPreExecute();
//display progressdialog.
}
protected Integer doInBackground(Integer ...code){
try {
URL u = new URL ( "http://www.reddit.com/r/notarealurlinredditqwerty");
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("POST");
HttpURLConnection.setFollowRedirects(true);
huc.connect();
code[0] = huc.getResponseCode();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return code[0];
}
protected void onPostExecute(Integer result){
super.onPostExecute(result);
//dismiss progressdialog.
}
}
That is my Async task for checking. Here is the code implementing it:
int code = -1;
Checker checker = new Checker();
try {
code = checker.execute(code).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("code:", "" + code);
That log always returns 200, but I know that URL is 302 (it redirects to a search page on reddit.com).
What am I doing wrong?
This line just needs to be set to false:
HttpURLConnection.setFollowRedirects(false);
You can use HttpURLConnection. I have used it for response code in a few applications. I did not encounter any problems.
URL url = new URL("http://yoururl.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();

Categories

Resources