So I am trying to download and load an object from a file stored on a webserver. The code I use is inside a try-catch block in an AsyncTask:
URL url = new URL("http://www.mydomain.com/thefileIwant");
URLConnection urlConn = url.openConnection();
ObjectInputStream ois = new ObjectInputStream(urlConn.getInputStream());
foo = (Foo) ois.readObject();
ois.close();
I build the file with this code:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("thefileIwant"));
oos.writeObject(foo);
oos.close();
When I try and read the object in the first piece of code I get an IOExecption that the UTF Data Format does not match UTF-8. I have tried re-building the file a couple of times and it always gives me the same error. Can I download an Object like this?
This looks like an encoding problem. I think kichik is right and most likely your server is sending data using the wrong content type, but I think you'll need to set it to application/x-java-serialized-object
instead.
Try adding the following lines right after opening the URLConnection:
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/x-java-serialized-object");
If that doesn't work (your server may not be able to sent it using that type) you can either try to use Socket instead of UrlConnection, or else serialize your object using XML or JSON and get that via HttpUrlConnection
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With