What exceptions should be captured when reading web file - android

Update 1
main.java file
//how would i return those errors on the main.java file? so that i can display on the UI.
directory_listings = obj.get_webpage_source();
end
I am new to Android mobile application development. I would like to know, how can I handle the exception like HttpConnection related exceptions or any other important exceptions.
i am thinking of top of my head:
server is down
file not exists
no data found
my code is here:
the below code is in its own java class and i am calling this code from main.java
public class Get_Webpage {
public String get_webpage_source(){
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(parsing_url);
HttpResponse response = null;
...............
...............
...............
}
}

you need to catch all the below exception when reading file from the web.
try
{
}
catch (SocketTimeoutException e) {
e.printStackTrace();
return "error";
}
catch (ConnectTimeoutException e)
{
e.printStackTrace();
return "error";
}
catch (ClientProtocolException e)
{
e.printStackTrace();
return "error";
}
catch (IOException e)
{
e.printStackTrace();
return "error";
}
finally {
client.getConnectionManager().shutdown();
}

Related

How to catch FileNotFoundException from MediaPlayer?

I am using a MediaPlayer that grabs videos from URLs:
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(this, uri);
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
When I try and set a datasource with a url, that for instance, has been taken down, I get the following error in my logcat:
Couldn't open file on client side; trying server side:
java.io.FileNotFoundException: No content provider:
http://example.com/examplevideo.mp4
However, my catch{} does not trap this in the following code above, which I need it to do so I can display an error message etc...
Is there any way to catch this FileNotFoundException in my code?
Thanks in advance
I don't know how to catch this specific exception. But you can use following to catch any type of exception.
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(this, uri);
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(this, uri);
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
Log.i("your tag",e.toString());
}
and look at the log with the tag you whant
Thanks all for replies.
I forgot to mention that the file is from an external server, but have adopted an approach similar to what Pramod suggested, but altered to suit my needs.
/**
* Checks if an external file on a server exists.
* #param urlString The file URL
* #return true if file exists, false if does not
*/
public boolean checkExternalFileExists(String urlString){
try {
URL url = new URL(urlString);
int response = ((HttpURLConnection)url.openConnection()).getResponseCode();
return response == HttpURLConnection.HTTP_OK;
}
catch (FileNotFoundException e) {
return false;
}catch (MalformedURLException e) {
return false;
} catch (IOException e) {
return false;
}
}
Thanks

How to get message from Exception?

Following is my piece of code:\
public void LoadProjectFile(String Filename) throws Exception
{
// m_Renderer.m_Project=new Project();
refresh_project();
m_Renderer.m_SelectedProjectPath = Filename;
try {
m_Renderer.m_Project.load_file(Filename);
}
catch (Exception e)
{
//Exception a = e.getMessage();
String a= e.getMessage();
throw new Exception(a);
}
//AppFuncs.m_GisProject=m_Renderer.m_Project;
}
try
{
Map.this.mGLView.LoadProjectFile(AppFuncs.g_path);
Map.this.mGLView.requestRender();
}
catch (Exception e)
{
br=1;
b=e.getMessage();
}
Load project file throws an exception which i recieve in Map class. This exception contains message: Java.lang.exception: java.lang.exception: file not found.
I want to show only "File not found" message. so how should i get this message out from an exception?
Catch all types of exceptions instead of base Exception:
try {
m_Renderer.m_Project.load_file(Filename);
}
catch (FileNotFoundException e)
{
String a= "File not found"
throw new Exception(a);
}
catch (SomeOhterException e){
String a= "Some other message"
throw new Exception(a);
}
//at the end, but it shouldn't be necessary
catch (Exception e){
String a= "Something happend we don't know what"
throw new Exception(a);
}
Shortly: Use different class for different exception to show correct information rahter than using exception message.
Just catch the FileNotFoundException instead of an Exception.
For example:
try {
//whatever
} catch (FileNotFoundException e) {
System.out.println("File not found");
}

Http delete gets bad request in Android

I am working with Android http stuff to register/unregister to the server. I have a DELETE request to use HttpDelete. I am getting Http401 'Bad request' error when I try to call it. I cannot why it is happening. Please help me.
Here is my code:
HttpUtils.java
private BasicHttpParams mParams;
private UsernamePasswordCredentials mCredentials = null;
private ResponseHandler mResponseHandler = null;
public void setUserCredentials(String userName, String password) {
this.mCredentials = new UsernamePasswordCredentials(userName, password);
}
public void setResponseHandler(ResponseHandler responseHandler){
this.mResponseHandler = responseHandler;
}
public Result<String> delete(String url){
Result<String> result = new Result<T>();
result.setStatus(Result.FAIL);
try {
DefaultHttpClient httpClient = new DefaultHttpClient(mParams);
httpClient.setParams(mParams);
httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), mCredentials);
HttpResponse response = httpClient.execute(new HttpDelete(url));
result.setResult(mResponseHandler.handleResponse(response));
result.setStatus(Result.SUCCESS);
} catch (IllegalArgumentException e) {
e.printStackTrace();
result.setMessage(e.getMessage());
} catch (ClientProtocolException e) {
e.printStackTrace();
result.setMessage(e.getMessage());
} catch (ConnectTimeoutException e) {
result.setMessage("Connection timed out.");
} catch (IOException e) {
e.printStackTrace();
result.setMessage(e.getMessage());
}
return result;
}
UnregisterTask.java
#Override
protected Void doInBackground(String... urls) {
if (urls==null || urls.length!=1)
return null;
String url = urls[0];
HttpUtils httpUtils = new HttpUtils();
httpUtils.setUserCredentials("userid", "password");
httpUtils.setResponseHandler(new UnrgisterHandler());
httpUtils.delete(url);
Result<String> result = aClient.delete(url);
if (result!=null || result.result != null){
//Do Something
}
}
//UnrgisterActivity.java
public void onUnregisterButtonClick(View view){
UnregisterTask task = new UnregisterTask(this);
task.execute(ServerConfig.getIdmServer() + ServerConfig.DELETE_DEVICE + "myid");
}
Error recevied:
Apache Tomcat/7.0.26 - Error report HTTP Status 400 - type Status reportmessage description The request sent by the client was syntactically incorrect ().Apache Tomcat/7.0.26
Thanks in Advance.
I fixed it by myself but I do not understand clearly why the error happened. I changed my code after searching how to set basic authentication.
public Result<T> delete(String url)
Result<T> result = new Result<T>();
result.setStatus(Status.FAIL);
try {
DefaultHttpClient http = new DefaultHttpClient();
if (this.mCredentials!=null){
CredentialsProvider credProvider = new BasicCredentialsProvider();
credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), this.mCredentials);
http.setCredentialsProvider(credProvider);
}
HttpDelete delete = new HttpDelete(url);
//delete.setEntity(new StringEntity(data, "UTF8"));
delete.addHeader("Content-type", JSON_TYPE);
HttpResponse response = http.execute(delete);
result.setResult(mResponseHandler.handleResponse(response));
result.setStatus(Result.Status.SUCCESS);
} catch (IllegalArgumentException e) {
e.printStackTrace();
result.setMessage(e.getMessage());
} catch (ClientProtocolException e) {
e.printStackTrace();
result.setMessage(e.getMessage());
} catch (ConnectTimeoutException e) {
result.setMessage("Connection timed out.");
} catch (IOException e) {
e.printStackTrace();
result.setMessage(e.getMessage());
}
return result;
}
A bit still confusing. Anyway, now it works charm.

Android webservice GET request replies only a part of the XML response

I'm trying to connect to a webservice offered by my heating at home. Putting the request URL into Chrome results in a complete XML file.
Subsequently I tried to do the same programmatically with an Android application, which unfortunately only replies about the half of the XML file.
I already tried several attempts, amongst others a simple HttpConnection:
private void androidHttpConnect() {
HttpURLConnection urlConnection=null;
try {
URL url = new URL("http://10.0.0.140:8080/user/menu");
urlConnection = (HttpURLConnection) url.openConnection();
BufferedInputStream in = new BufferedInputStream(
urlConnection.getInputStream());
Log.i("myapp",convertStreamToString(in));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
}
private String convertStreamToString(InputStream is) {
return new Scanner(is).useDelimiter("\\A").next();
}
and the Android Http Client ...
HttpClient httpclient = AndroidHttpClient.newInstance("Android");
HttpGet httpget = new HttpGet("http://10.0.0.140:8080/user/menu");
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
Log.d("myapp", "content length "+len);
if (len != -1) {
try {
Log.d("myapp", EntityUtils.toString(entity));
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Stream content out
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Interestingly those attempts cut the result on different positions, even though they only differ in about 5 characters. At this position there is no special character and the XML is quite short.
Anyone any idea? I also tried to run it in a ASyncTask to ensure no interrupt by the UI thread, but without success.
Thanks for your help.
Finally found the solution by myself! The problem wasn't the request but the output in the LogCat. Logging every line separately obtained the desired full response!

How can I check if a file exists on FTP server?

I am using apache FTPClient on android. I want to download a file from ftp server. But I want check if it exists on server before downloading. How can I check this?
Thanks,
my code:
public static boolean getFile(String serverName, String userName,
String password, String serverFilePath, String localFilePath)
throws Exception {
FTPClient ftp = new FTPClient();
try {
ftp.connect(serverName);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return false;
}
} catch (IOException e) {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
throw e;
}
}
throw e;
} catch (Exception e) {
throw e;
}
try {
if (!ftp.login(userName, password)) {
ftp.logout();
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
OutputStream output;
output = new FileOutputStream(localFilePath);
ftp.retrieveFile(serverFilePath, output);
output.close();
ftp.noop(); // check that control connection is working OK
ftp.logout();
return true;
} catch (FTPConnectionClosedException e) {
throw e;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw e;
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
throw f;
}
}
}
}
String[] files = ftp.listnames();
look files if desired file name is include...
Assuming ftpClient is an instance of org.apache.commons.net.ftp.FTPClient:
public boolean fileExists(String fileName) throws IOException
{
String[] files = ftpClient.listNames();
return Arrays.asList(files).contains(fileName);
}
When the client sends RETR and the server responds with an error code 550 you can be pretty sure that the file does not exist or you don't have permission to fetch it... Since the FTP spec is a little loose you might just assume for any error in the range 550 - 559 which indicates permanent filesystem error.
InputStream inputStream = ftpClient.retrieveFileStream(filePath);
if (inputStream == null || ftpClient.getReplyCode() == 550) {
// it means that file doesn't exist.
}
or
FTPFile[] mFileArray = ftp.listFiles();
// you can check if array contains needed file

Categories

Resources