mardi 7 avril 2015

Java: use getcontentLength() of URL in non static method


Vote count:

0




So I have this rather weird problem with my program. What I try to do is to check the contentLength of an URL and then use this number in a non-static method with an if-else statement connecting other classes. But my problem with this is that while I was researching the internet to somehow solve this problem, there where these static-methods that I could use to get the contentLength and it wouldn't work with non-static. So I tried it but I never really got any results. What I basically tried to do is to call the class with the static-method via non-static-method in another class which, I guess, shouldn't be the problem (or should? I don't really know since I have never worked with static methods before). Then I used this code to determine the contentLength of a random webpage with changing date:



public static void main() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 1); // Adding 1 day
String output = sdf.format(c.getTime());

try {
String urlStr = "http://ift.tt/1FyuPjr" + output + ".pdf";
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int contentLength = httpConn.getContentLength();
if (contentLength < 2000) {
new NotWorkingActivity();
System.out.println("unknown content length");
} else {
new download2Activity();
System.out.println("content length: " + contentLength + " bytes");
}
InputStream inStream = httpConn.getInputStream();
// now read data
// ...

// close connection
httpConn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}


Afterwards, when the size of the page was determined to be smaller than 2000 bytes, it should show a Toast in another class that the page is not available, but when it was bigger, then it should open up a new class, as you may see in the else-statement. But it doesn't work and I think I just messed up with static methods. I'm just not that experienced with them. Sorry for any other mistakes that I might have made. If there is an different solution to my problem which, hopefully, is easier to understand and better to use, I would be very grateful.


Please, I need help on this problem and I hope you understand what I am up to. Thanks in advance :)



asked 2 mins ago







Java: use getcontentLength() of URL in non static method

Aucun commentaire:

Enregistrer un commentaire