因此,我尝试从存储在and服务器上的文件中下载并加载一个对象。我使用的代码在AsyncTask中的try-catch块中:
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();
我使用以下代码构建文件:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("thefileIwant"));
oos.writeObject(foo);
oos.close();
当我尝试读取第一段代码中的对象时,我得到一个UTF数据格式与UTF-8不匹配的IOExecption。我尝试了几次重新构建该文件,但总是出现相同的错误。我可以下载这样的对象吗?
发布于 2012-05-18 21:19:31
这看起来像是编码问题。我认为kichik是正确的,很可能您的服务器使用错误的内容类型发送数据,但我认为您需要将其设置为application/x-java-serialized-object
。尝试在打开URLConnection后立即添加以下行:
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/x-java-serialized-object");
如果这样做不起作用(您的服务器可能无法使用该类型发送),您可以尝试使用套接字而不是UrlConnection,或者使用XML或JSON序列化对象并通过HttpUrlConnection获取
发布于 2012-05-22 02:58:39
尝尝这个。它与您的代码相似,但有一些不同之处。顺序读/写可能有点过时,但对我来说工作得很好。
URL url = new URL("your URL");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
urlConn.connect();
InputStream is = urlConn.getInputStream();
byte[] buffer = new byte[1024];
int numRead = 0;
FileOutputStream fos = new FileOutputStream("Your File");
while ((numRead = is.read(buffer)) > 0) {
fos.write(buffer, 0, numRead);
}
fos.close();
发布于 2012-05-25 05:49:01
这对我们来说是可行的,使用一些Apache库
FileOutputStream fos = new FileOutputStream("Your File");
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
HttpClient client = new DefaultHttpClient(ccm, params);
HttpGet httpGet = new HttpGet(downloadURL);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
Log.d(LOG_TAG, "code is " + statusCode);
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = content.read(buffer)) > 0 ) {
fos.write(buffer,0, len1);
}
success = true;
} else {
Log.e(LOG_TAG_JSON, "Failed to download file " + downloadURL);
}
if (null != response.getEntity())
{
response.getEntity().consumeContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, "downloadVersion " + e.toString());
e.printStackTrace();
}
https://stackoverflow.com/questions/10556655
复制相似问题