【发布时间】:2011-07-08 18:13:41
【问题描述】:
我在以下代码中收到 MalformedURLexception,我不知道是什么原因造成的。
public void down(String url)
{ try {
URL url1 = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"somefile.ext");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//report progress
}
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
它说未知协议。 在阅读部分出现之前,连接完全正常, 在此之前,代码甚至可以打印正确大小的文件。 我要下载的文件也有一个像 http://download12.aomethin.com/blaa-blaa 如果我尝试添加 www,请求开始重定向。 虽然我认为这可能是一个菜鸟,但我也想知道如何获取此文件的名称并使用该名称而不是我选择的名称保存文件。
编辑:程序现在正在运行,我只需要知道如何获得正确的文件名。并使其成为后台进程。
【问题讨论】:
-
@home 我现在添加堆栈跟踪是不是错了...
-
@rigy73 你的堆栈跟踪在哪里?
-
@Alex 嘿,我又试了一次,程序正在运行,正在下载文件,但发生这种情况时,应用程序似乎挂起。我该如何改变它。
-
@rigy73 这就是我的意思:运行 DDMS,点击“E”,这样你只会看到错误。然后单击清除日志。接下来,运行您的程序,当它崩溃时,您应该会看到那里弹出一些东西。选择与您的应用相关的所有内容并将其粘贴到此处。
-
@rigy73 我不知道您所说的“获取正确名称”是什么意思,但如果它挂起,您可能希望在单独的线程中进行下载,请参阅:developer.android.com/resources/articles/…
标签: android file download malformedurlexception