Intercept response code in webview using google doc to display pdf - android

I have a webview that loads a google doc with a flyer (pdf, from the web) in it. Some of the flyers are live on my website but others aren't, but I have them coded in the app so when they become available the user will see them.
The google doc in the webview works great with flyers that are available but ones that aren't available yet I get a error-type message in the google doc. I would like to intercept the 404 response code error from the URL that has the flyer (pdf). How do I do this?
Current code:
/*opens in app using google docs*/
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginState(PluginState.ON);
mWebView.loadUrl("https://docs.google.com/viewer?url="+round_num_url);
//round_num_url is the url for my flyer
Message in google doc in webview for flyers unavailable - "Sorry, we were unable to find the document at the original source. Verify that the document still exists. You can also try to download the original document by clicker here"
EDIT: doesn't work yet (crashes) after taking suggestions from #x-code
try {
URL url = new URL(round_num_url);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("HEAD");
huc.connect();
if (huc.getResponseCode() != 404) {
// the pdf is available, continue with your code that loads the web view
// ...
} else {
// the pdf is not available, you may need to notify the user
// ...
}
huc.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}

Although Google docs will receive a 404 when it tries to access your broken URL, it is not going to return a 404 to the web view, because the Google docs URL is valid.
You should first test your own URL (the URL of your PDF) by trying to load it with for example the AndroidHttpClient and an HttpHead request. If this returns a 404 don't bother trying to load gdocs.
Here is some example code. I used HttpUrlConnection because that is the method recommended by Android docs for new code:
HttpUrlConnection huc = new HttpUrlConnection(round_num_url);
huc.setRequestMethod("HEAD");
huc.connect();
if (huc.getResponseCode() != 404) {
// the pdf is available, continue with your code that loads the web view
// ...
} else {
// the pdf is not available, you may need to notify the user
// ...
}
huc.disconnect();
I have not compiled this code, and you may have to wrap it in a try / catch block before it will compile.
Update: I had to modify the code to make it work, as suggested above:
try {
URL url = new URL(strUrl);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
try {
if (huc.getResponseCode() != 404) {
// url is available
} else {
// url is not available
}
} finally {
huc.disconnect();
}
} catch (MalformedURLException e) {
;
} catch (IOException e) {
;
}

Related

Prevent java.lang.IllegalArgumentException: Host name may not be null

When executing an HttpUriRequest using the AndroidHttpClient, it will throw an java.lang.IllegalArgumentException: Host name may not be null when the url is faulty.
In my application, the user can input his own url. When for example http://195.168.0.q is entered, the IllegalArgument is thrown, and the app crashes.
How can I prevent this (preferably, without catching exceptions)?
Catch the exception with a 'try-catch(-finally)' block.
try {
// your code
} catch(IllegalArgumentException) {
// Faulty url
}
You should make sure the user has supplied a valid URL before trying to use it as one:
URL url;
try {
url = new URL("http://195.168.0.q");
} catch (MalformedURLException e) {
// tell user the URL they entered is invalid
}

Trying to verify person specific url then bring up login screen in Android

I'm trying to make an application where the person connects to their specific website and can then access the data from it. The first page asks them to put in the url. I then parse this and need to verify the url's existence so I can move them to the login screen. How do I go about doing this? I'm trying HttpURLConnections but I'm not having much luck. Thoughts?
Try the below code :
try {
int status = 0;
try {
HttpURLConnection httpConnection = (HttpURLConnection) new URL(
"http://www.google.com").openConnection();
httpConnection.setRequestMethod("HEAD");
Log.e("StatusCode",httpConnection.getResponseCode());
if ((httpConnection.getResponseCode() == 200)||(httpConnection.getResponseCode() == 302)) {
status = 1;
}
} catch (Exception ex) {}
if (status == 1) {
Log.e("WebSite","Found");
} else {
Log.e("WebSite","NotFound");
}
} catch (Exception ex1) {
Log.e("Error",ex1.getMessage().toString());
}

Android - How to parse RSS Feed from .net website?

I'm using this method to read RSS Feeds from URL. Everything works fine except it fails to get feeds from .net webserver (eg. http://www.dotnetnuke.com/Resources/Blogs/rssid/99.aspx).
public String getRSSLinkFromURL(String url) {
// RSS url
String rss_url = null;
try {
// Using JSoup library to parse the html source code
org.jsoup.nodes.Document doc = Jsoup.connect(url).get();
// finding rss links which are having link[type=application/rss+xml]
org.jsoup.select.Elements links = doc.select("link[type=application/rss+xml]");
Log.d("No of RSS links found", " " + links.size());
// check if urls found or not
if (links.size() > 0) {
rss_url = links.get(0).attr("href").toString();
} else {
// finding rss links which are having link[type=application/rss+xml]
org.jsoup.select.Elements links1 = doc.select("link[type=application/atom+xml]");
if(links1.size() > 0){
rss_url = links1.get(0).attr("href").toString();
}
}
} catch (IOException e) {
e.printStackTrace();
}
// returing RSS url
return rss_url;
}
You RSS feed is broken: transfer closed with outstanding read data remaining.
curl will return that message when the socket has been closed before
the final terminating chunk of a chunky transfer is read. It sure
sounds like a server bug to me.
Source: [Re: transfer closed with outstanding read data remaining with Expect: 100-continue][1]
Fix (workaround) for JSoup is here:
https://github.com/jhy/jsoup/pull/323

Android HttpURLConnection VERY slow

This is the situation I'm facing with the code below:
As you can see I'm trying to read an HTTP stream. When I run the following code on the Android simulator it works 100% of the time, when I run the following code on my Galaxy S3 while on 3G it works 100% of the time, when I try to connect to the URL using my laptop browser it works 100% of the time, when I try to connect using the Galaxy S3 browser (in both wifi and 3g) it works... 100% of the time. HOWEVER, when I try to connect using my Galaxy S3 while on Wi-Fi I time out ~80% of the time. If I remove the timeout properties I get weird exceptions such as:
"recvfrom failed: ETIMEDOUT"
"failed to connect to <URL>: connect failed: ENETUNREACH (Network is unreachable)"
"unable to resolve the host <URL>: no address associated with hostname"
I'm open to any suggestions...
public static final String getHttpResponse(String url)
{
HttpURLConnection conn = null;
InputStream response = null;
try {
URL address = new URL(url);
conn = (HttpURLConnection)address.openConnection();
conn.setConnectTimeout(30 * 1000); //30 seconds
conn.setReadTimeout(30 * 1000); //30 seconds
response = conn.getInputStream();
if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e("Util.getHttpResponse", Integer.toString(conn.getResponseCode()));
return null;
}
String result = Util.streamToString(response);
return result;
} catch(IOException e) {
response = conn.getErrorStream();
Log.e("Util.getHttpResponse", Util.streamToString(response));
return null;
} finally {
if( response != null ) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null) {
conn.disconnect();
}
}
}
UPDATE:
- using AndroidHttpClient did not work
- After getting the input stream I had an error popup right in the eclipse IDE... As you can see my debug cursor made it all the way to line 107.. well after I was done getting the input stream this time...
I got the same problem on Android device. I use an IP address in the url. Final, I found the HttpURLConnection.connect(...) method involved the getHostName() internally. After that, I use the domain in the url, then it works 100% of the time.
As an experiment, what if you try using AndroidHttpClient class instead for doing the same? It has some predefined timeouts and other settings which, we were told, should work fine in most cases.

App works fine in wifi but doesn't work in 3g

i'm a new Android developer and I'm developing an application that display image from an url adress. It works fine in wifi but doesn't work in 3g.
Here's the code :
private void downloadImage(String urlPar, boolean imageSuivant) {
try {
URL urlImage = new URL(urlPar);
HttpURLConnection connection = (HttpURLConnection) urlImage.openConnection();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
image.setImageBitmap(bitmap);
connection.disconnect();
inputStream.close();
} catch (MalformedURLException e) {
if(imageSuivant==true)
imageSuivante();
else
imagePrecedente();
e.printStackTrace();
} catch (IOException e) {
if(imageSuivant==true)
imageSuivante();
else
imagePrecedente();
e.printStackTrace();
}
}
can you open the image whith the html-browser?
if not the image-url is not reachable from the internet but only from wlan-intranet. (i.e. http://192.168.117.18/myImage.jpg is not reachable from internet (3G)
A few times I have found that my phone operator does not allow certain type of files to be accessed. For example it was impossible for me to get an archive file (.zip) from the web in 3G but it worked fine in Wifi.
Maybe your problem is similar. Check your image file type and try with other types of files.
Try
conn.setDoOutput(true);
connection.setAllowUserInteraction(true);
Hope this would help

Categories

Resources