Java 'TimeoutException' can't be thrown or catched - java

I am developing an android app that reads a webpage using AsyncTask.I have 2 AsyncTask classes that reads different page, one inside service, other not.In both cases url connection method is enclosed inside try-catch block , but their catch blocks are different(TimeoutException catch block missing in the 2nd AsyncTask class, tried to catch or throw it manually but failed) .Even though their connection methods are same, their try-catch blocks are different, but I need to catch TimeoutException in both task.
Here is part of my 1st AsyncTask class
try {
url=new URL(link);
huc=(HttpURLConnection) url.openConnection();
huc.setRequestMethod("GET");
huc.setDoOutput(true);
huc.setReadTimeout(READ_TIMEOUT);
huc.connect();
dothework();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
showErrorMsg();
e.printStackTrace();
}
and part of 2nd AsyncTask class
try {
url = new URL(link);
HttpURLConnection huc=(HttpURLConnection) url.openConnection();
huc.setReadTimeout(5000);
huc.setDoOutput(true);
huc.setRequestMethod("GET");
huc.connect();
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}

I'm not sure, but I think a HttpConnection is a AsyncTask already. So, I think you're making a call to an AsyncTask inside another.

Related

How to catch an Exception and a SocketTimeOut Exception in one try/catch block

I have implemented a try catch block for URLconnection as well as Parser class as follow.
try {
Url uri = new Url(urlString);
Parser parse = new Parser(uri);
} catch (Exception e)
{
//ignore some other exceptions
}
catch (SocketTimeOutException e)
{
//I want to catch this exception and do some thing or restart
//if it's a timeout issue.
//I am using a proxy for the network connection at JVM setting
//using setProperty
}
So , my question is how to act accordingly based on the SocketTimeOutException case , and for other Exception ignore .
Thanks ,
As java specification says (http://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html#jls-11.2.3 and http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20), first matched, first executed.
Simply invert your catch clause :
try {
Url uri = new Url(urlString);
Parser parse = new Parser(uri);
} catch (SocketTimeOutException e) {
//I want to cache this ecption and do some thing or restart based
//if its timeout issue
//am using proxy for the network connection at JVM setting
//using setProperty
} catch (Exception e) {
//ingnore some other excpetions
}
Put more specific exception types above more general types, so put the SocketTimeoutException catch clause above Exception
Catch the SocketTimeOutException first:
try {
// do stuff
} catch (SocketTimeOutException e) {
// restart or do whatever you need to do
} catch (Exception e) {
// do something else
}
How to catch an Exception and a SocketTimeOut Exception in one try/catch block?? If you wan't to have only one catch block then you can do like this
try {
URI uri = new URI(urlString);
Parser parse = new Parser(uri);
} catch(Exception e) {
if (e instanceof SocketTimeoutException) {
// do something
}
}

Getting a 405 response code with HttpURLConnection

I am getting a HTTP response code 405 when I use HttpURLConnection to make a DELETE request:
public void makeDeleteRequest(String objtype,String objkey)
{
URL url=null;
String uri="http://localhost:8180/GoogleMapsLoadingTest/rest/GoogleMapsErp/";
HttpURLConnection conn=null;
try {
url=new URL(uri);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn=(HttpURLConnection) url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.setDoInput(true);
conn.setDoOutput(true);
try {
System.out.println(conn.getResponseCode());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conn.setRequestMethod("DELETE");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How can I make this request?
The 405 status code means that your method (DELETE) is not allowed for the resource you specified; in this case, what looks like an entire REST endpoint directory. You should use DELETE on the specific item you want deleted; perhaps you forgot to actually use the method parameters when constructing the URL?
It would appear to be a problem with your server. I'm guessing nginx, but let me know if not.
Take a look here to see how to compile ngninx with HttpDavModule. There are other servers that have issues with this, but nginx doesn't have it by default.
If you're running Apache, check your module configurations to see if you're disallowing them or not. Here's a post about a previous solution. Unfortunately, this problem is typically specific to modules that have been installed. On a vanilla installation, however, you can often just allow for DELETE (see your config file, as well as the OP of that link)

Android loading from file Error

I am getting the occassional error message when I try to read a serialized object from a file. It works fine 9 times out of 10, but for some reason I get lots of these error message sin the catlog:
06-01 23:57:50.824: ERROR/MemoryFile(16077): MemoryFile.finalize() called while ashmem
still open
and
06-01 23:57:57.664: ERROR/MemoryFile(16077): java.io.IOException: munmap failed
The second message comes with no indication where the exception is caused. (Clearly when I'm loading the file, but I already have a try/catch around it.)
My loadfile method looks like this:
public TGame loadSavedGame(){
TGame g=null;
InputStream instream = null;
BufferedReader br=null;
InputStreamReader inputreader=null;
try {
File sdCard = Environment.getExternalStorageDirectory();
instream = new
FileInputStream(sdCard.getAbsolutePath()+"/egyptica/serializationtest");
// inputreader = new InputStreamReader(instream);
// br= new BufferedReader(inputreader);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
try {
ObjectInputStream ois = new ObjectInputStream(instream);
try {
g= (TGame) ois.readObject();
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return g;
} catch (ClassNotFoundException ex) {
// TODO Auto-generated catch block
android.util.Log.e("DESERIALIZATION FAILED (CLASS NOT
FOUND):"+ex.getMessage(), "ex");
ex.printStackTrace();
return null;
}
} catch (StreamCorruptedException ex) {
android.util.Log.e("DESERIALIZATION FAILED (CORRUPT):"+ex.getMessage(),
"ex");
// TODO Auto-generated catch block
ex.printStackTrace();
return null;
} catch (IOException ex) {
android.util.Log.e("DESERIALIZATION FAILED (IO
EXCEPTION):"+ex.getMessage(), "ex");
// TODO Auto-generated catch block
ex.printStackTrace();
return null;
}
}
One possibility I have thought of is using a BufferedReader to rea the file. However I'm not sure how to go about doing this. Any help would be appreciated.
Try to put finally block after try and put there closing statements for your streams and also useful thing is to use:
FileInputStream.getFD().sync();
It makes sure that file really received your close/flush

Can't get Android 2.3 to handle GZIp

Having some issue with Android 2.3 not picking up the Content-Encoding header from our server.
See http://pastebin.com/v0Jvn0nD for a comparison with 2.2 and 2.3.
So, I am trying to get a workaround so Android can handle the GZIP, at the moment it just fails. Here is the connection logic:
Any help would be cool. Many thanks
URL test = null;
try {
test = new URL(url);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
URLConnection connection = null;
try {
connection = test.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream stream = null;
try {
stream = connection.getInputStream();
Log.d("HttpHelper","getContentEncoding: " + connection.getContentEncoding()); // RETURNING NULL ON 2.3
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if ("gzip".equals(connection.getContentEncoding())) { // NULL HERE ON 2.3
try {
stream = new GZIPInputStream(stream);
responseString = textHelper.getText(stream);
globallistener.onComplete(responseString);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Transfering text data to a web server using Java

I'm trying to write to a text file on my web server using HttpURLConnection.getOutputStream(). I have tried this on two different servers without success.
I have added a FileWriter to test the InputStream, and that file is created on a local directory correctly, but nothing is showing up on the in the web server directory, even with all password protection off.
Any help would be greatly appreciated.
URL url;
try {
url = new URL("http://www.myWebsite.com/myFile.txt");
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
OutputStream in = new BufferedOutputStream(urlConnection.getOutputStream());
InputStream fin1;
try {
fin1 = new FileInputStream(Environment.getExternalStorageDirectory() + "/fileToRead.txt");
FileWriter fWriter = new FileWriter(Environment.getExternalStorageDirectory() + "/fileToWrite.txt");
int data = fin1.read();
while(data != -1) {
fWriter.write(data);
in.write(data);
data = fin1.read();
}
fWriter.flush();
fWriter.close();
fin1.close();
in.flush();
in.close();
} catch (FileNotFoundException e31) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
} catch (IOException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
} catch (MalformedURLException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
You have to call getInputStream() on the urlConnection in order to get the output stream to flush out the socket to the remote server.
See the discussion here: Why do you have to call URLConnection#getInputStream to be able to write out to URLConnection#getOutputStream?
You are catching the IOException (Right after the IOException) but are not doing anything with it. At least print the stack trace.
You can also use Apache's Http Client http://hc.apache.org/httpcomponents-client-ga/index.html
Much easier than getting URLConnection to work.

Categories

Resources