我在以下代码中收到 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的 url 如果我尝试添加 www,请求开始重定向。虽然我认为这可能是一个菜鸟,但我也想知道如何获取此文件的名称并使用该名称而不是我选择的名称保存文件。
编辑:程序现在正在运行我只需要知道如何获得文件的正确名称。并使其成为后台进程。