Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Download Object

Tags:

java

android

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?

like image 634
Flynn Avatar asked May 11 '12 18:05

Flynn


1 Answers

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

like image 196
THelper Avatar answered Oct 16 '22 13:10

THelper