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();
Related
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;
}
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;
}
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();
Let's say there is a 3rd party RESTful web service exposing a GET endpoint at:
http://someservice.com/api/askAnyQuestion
And I want to hit that service, placing my question on the query string:
http://someservice.com/api/askAnyQuestion&q=Does%20my%20dog%20know%20about%20math%3F
How do I hit this service from a client-side GWT application? I've been reading the RequestFactory tutorials, but RF seems to be only for providing a data access layer (DAL) and for CRUDding entities, and I'm not entirely sure if it's appropriate for this use case.
Extra super bonus points if anyone can provide a code sample, and not just a link to the GWT tutorials, which I have already read, or some Googler's blog, which I have also probably read ;-).
You can use RequestBuilder. Successfully used it to work with REST.
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
builder.sendRequest(null, new RequestCallback() {
#Override
public void onError(Request request, Throwable exception) {
// process error
}
#Override
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// process success
} else {
// process other HTTP response codes
}
}
});
} catch (RequestException e) {
// process exception
}
Please also take a look at this question for cross site requests related info.
I had the same problem few days ago and tried to implement it with requestBuilder. You will receive a Cross-Domain Scripting issue.
https://developers.google.com/web-toolkit/doc/1.6/FAQ_Server#How_can_I_dynamically_fetch_JSON_feeds_from_other_web_domains?
I did handle this by a RPC Request to my Server, and from there a Server-Side HTTP Request to the Cross-Domain URL.
https://developers.google.com/web-toolkit/doc/latest/tutorial/Xsite
public static void SendRequest(String method, String notifications) {
String url = SERVICE_BASE_URL + method;
JSONObject requestObject = new JSONObject();
JSONArray notificationsArray =null;
JSONObject mainRequest = new JSONObject();
try {
notificationsArray = new JSONArray(notifications);
requestObject.put("notifications", notificationsArray);
mainRequest.put("request", requestObject);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpURLConnection connection = null;
try
{
URL server = new URL(url);
connection = (HttpURLConnection) server.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.writeBytes(mainRequest.toString());
writer.flush();
writer.close();
parseResponse(connection);
}
catch (Exception e)
{
System.out.println("An error occurred: " + e.getMessage());
}
finally
{
if (connection != null)
{
connection.disconnect();
}
}
}
This question already has answers here:
Checking if a URL exists or not
(4 answers)
Closed 6 years ago.
How can I check in Java if a file exists on a remote server (served by HTTP), having its URL? I don't want to download the file, just check its existence.
import java.net.*;
import java.io.*;
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
If the connection to a URL (made with HttpURLConnection) returns with HTTP status code 200 then the file exists.
EDIT: Note that since we only care it exists or not there is no need to request the entire document. We can just request the header using the HTTP HEAD request method to check if it exists.
Source: http://www.rgagnon.com/javadetails/java-0059.html
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
Checking if a URL exists or not
Check this, it works for me. Source URL: Check if URL exists or not on Server
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
MyTask task = new MyTask();
task.execute(customURL);
}
private class MyTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
}
#Override
protected Boolean doInBackground(String... params) {
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(params[0]).openConnection();
con.setRequestMethod("HEAD");
System.out.println(con.getResponseCode());
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
protected void onPostExecute(Boolean result) {
boolean bResponse = result;
if (bResponse==true)
{
Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
}
}
}
}
Assuming the file is being served through http, you can send a HEAD request to the URL and check the http response code returned.
The only true way is to download it :). On some servers usually you can get away by issuing a HEAD request insted of a GET request for the same url. This will return you only the resource metadata and not the actual file content.
Update: Check org.life.java's answer for the actual technical details on how to do this.
Make a URLConnection to it. If you succeed, it exists. You may have to go so far as opening an input stream to it, but you don't have to read the contents. You can immediately close the stream.