I am using following code to load public shared images from google drive to android app, but sometimes I got:
javax.net.ssl.SSLException: Read error: ssl=0x1d9ed0: I/O error during system call, Connection reset by peer
Why google drive is closing connection before I download image? This is happening randomly, but quite often. Does someone collide with such problem?
public static InputStream getStream(String url)
{
InputStream is = null;
try
{
is = new URL(url).openConnection().getInputStream();
} catch (MalformedURLException e)
{
L.e(e.toString());
} catch (IOException e)
{
L.e(e.toString());
}
return is;
}
For bitmap loading I use simple code:
BitmapFactory.decodeStream(stream, null, null);
It could be that you are affected by the following: The URL that you get from the file's metadata is short lived. If you are saving that URL to use later it won't work because it could be that the URL gets invalidated.
To do this you have to fetch the image metadata every time to get the new downloadURL.
We are working on providing non expirable URLs in the future.
Related
I just managed to upload some files to an FTP server using Apache Commons Net FTP. When I use everything as it should be it works fine, I mean, the file uploading is working, but when I use, for example, a wrong password for the FTP account, obviously the files don't get uploaded to the server, but I don't get an error message either. In other words: I don't know how to show the error. I tried to show with a toast the e.getMessage() from the Exception but nothing is shown. Is there any documentation that would help me? Or am I missing something you could help me with? thank you!
This is my code:
#Override
protected Void doInBackground(Void... voids) {
FTPClient ftpClient=new FTPClient();
try {
ftpClient.connect(fserver);
ftpClient.login(fusername,fpassword);
ftpClient.enterLocalPassiveMode();
dirArch = new ArrayList<>();
for (int k=0;k<adapter.getSelected().size();k++){
dirArch.add(adapter.getSelected().get(k).getArch());
}
for (String archTXT : dirArch){
File fileX =new File(stringFolder,archTXT);
InputStream inputStream=new FileInputStream(fileX);
ftpClient.storeFile(archTXT,inputStream);
inputStream.close();
pbPorc=pbPorc+pbSum;
pb1.setProgress(pbPorc);
pb2.setProgress(pbPorc);
}
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(ExportTracks.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
return null;
}
Your error handling is wrong.
The FTPClient.login does not throw an exception, when the credentials are wrong. It returns a false. You do not test for that. Your code carries on, trying to work with not authorized session instead, all of which will obviously fail too.
But as the same is true for FTPClient.storeFile, which also just returns false, your code basically does not notice any errors.
I am given a shortened url and I want to get the expanded form. The below java function is used to achieve this.
public String expand(String shortenedUrl){
URL url = null;
try {
url = new URL(shortenedUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// open connection
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
} catch (IOException e) {
e.printStackTrace();
}
// stop following browser redirect
httpURLConnection.setInstanceFollowRedirects(false);
// extract location header containing the actual destination URL
String expandedURL = httpURLConnection.getHeaderField("Location");
httpURLConnection.disconnect();
return expandedURL;
}
The code works fine in Eclipse but the same doesn't work in android.
String expandedURL = httpURLConnection.getHeaderField("Location");
The above line throws java.lang.RuntimeException: Unable to start activity ComponentInfo. And the error is pointed to the above line. If I remove the above line no error is encountered. Even I am not able to use getResponseCode() function.
int status = 0;
try {
status = httpURLConnection.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}
This piece of code also has the same problem. works in eclipse but not in android.
Any kind of help will be greatly appreciated.
Edit: The code using above function is,
ExpandUrl expandUrl = new ExpandUrl();
String expandedUrl = expandUrl.expand(shortenedUrl);
Note: The function expand is defined inside the class ExpandUrl.
Well, the code works in Eclipse but not in android. The reason is that you are doing it in Main thread and blocking it. Android wouldn't allow you to do so and throw runtime error.
I have tried to implement your code using AsyncTask in android. It works fine.
Give it a try.
To know more about AsyncTask follow: Android Documentation on AsyncTask
Good Luck!
I have a JEE 7 servlet that sends a picture from a networked web cam to the user's browser. If the camera is on, all is well and the image is sent. If the camera is off, my own "DeviceUnavailableException" is thrown. The servlet then sends an alternative image indicating that the camera is off-a kind of friendly visual error message. This is the code:-
protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
try {
ServletOutputStream os = response.getOutputStream(); // Cannot use try-with-resources here!
Camera camera = new Camera(ip, username, password);
byte[] vImage = camera.getEntropy();
response.setContentType("image/jpeg");
System.out.println("Sending visualisation...");
os.write(vImage);
os.close();
} catch (DeviceUnavailableException e) {
System.err.println(e);
try (InputStream is = PhotonicSignalVisualisation.class
.getResourceAsStream("unavailable.png");
ServletOutputStream os = response.getOutputStream()) {
byte[] uImage = new byte[623]; // need to know exact file size of wait.png
is.read(uImage);
response.setContentType("image/png");
System.out.println("Sending unavailable image...");
os.write(uImage);
} catch (IOException ex) {
System.err.println("No luck sending device unavailable image");
System.err.println(e);
}
} catch (IOException e) {
System.err.println(e);
}
}
This code works.
Weird thing is that whilst I can have a try-with-resources (TWR) statement in the DeviceUnavailableException catch block, I can't in the try block at the top. NetBeans suggests I convert to TWR, but when I do, no image is returned to the browser. It appears that os.write(uImage) is executed, but sent elsewhere, not to the browser!
I'm probably approaching this all backwards, but I can't understand the TWR issue here. Is there a better way to handle the friendly error situation? I was trying to avoid a simple broken image icon on the browser when the camera is off.
All the classes inside TWR block should implement AutoCloseable interface.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
The try-with-resources statement ensures that each resource is closed
at the end of the statement. Any object that implements
java.lang.AutoCloseable, which includes all objects which implement
java.io.Closeable, can be used as a resource.
Solution: Make your Camera Class implement AutoCloseable.
I'm trying to write a String to my webpage using Java in Android Studio by reusing some piece of codes of one Java Eclipse project which works well on my PC.
However, the String just cannot be written to the web page using my Android phone.
public void upload(String FTPaddress, String message){
try {
URL url = new URL(FTPaddress); // my server address
URLConnection urlc = url.openConnection();
OutputStream os = (OutputStream) urlc.getOutputStream(); // To upload
OutputStream buffer = new BufferedOutputStream(os);
buffer.write(message.getBytes());
buffer.close();
os.close();
} catch (FileNotFoundException e) {
// print in log
} catch (IOException e) {
// print in log
}
}
Please note that the function is executed, the mobile phone is connected to the internet, thus I am running it on another thread using asyncTask, and there is no exceptions
So can anyone tell me why it worked on my laptop but not for my mobile phone?
I use following code to call an Azure mobile backend API in my Android app,
try {
mobileClient.invokeApi("CustomTransaction", senderToCheck,
Boolean.class, new ApiOperationCallback<Boolean>() {
#Override
public void onCompleted(Boolean result,
Exception error, ServiceFilterResponse response) {
if (error == null) {
CheckSender(result);
} else {
dial.dismiss();
Crouton.makeText(MyActivity.this,
"Eror Occured with service",
Style.ALERT).show();
}
}
});
} catch (SecurityException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
e.printStackTrace();
} catch (IllegalArgumentException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
e.printStackTrace();
}
Other information:
CustomTransaction - API Controller name;
senderToCheck - JSON parsable data transfer object;
Boolean.class - return type; and 4th parameter is the callback method
All objects are JSON parsable and this worked like several days ago.
So this API call/Azure call always times out giving a What does "connection reset by peer" mean? ,SSLHandShakeExceptionand and most of the time Connect gets Timed out.
Main cause for the problem is com.microsoft.windowsazure.mobileservices.MobileServiceException: Error while processing request.
I tried re-publishing my asp.net web app several times but it never hits controller action where my debugger point is placed when debugging the service call remotely.
I checked if my service is down, found it is up & running then checked Azure management portal logs, found out traceApi messages of some controller action methods. and of SQL Cpu usages and Data out packet sizes., but I never gets a proper reply from anywhere to solve this problem for two weeks now.
In case,if I am correct, think the solution for this problem lies in http://www.webapper.com/blog/index.php/2007/02/09/troubleshooting-javaxnetsslsslhandshakeexception/ but Im not pretty sure on doing it.
Please advise me on getting this fixed