connection.getInputStream() 上的 FileNotFoundException; API 级别小于 23 的行
FileNotFoundExcption on connection.getInputStream(); line on API level less than 23
我正在使用 URLConnection 从服务器下载 HTML 文件,但出现 FileNotFoundException。我的路径是正确的。使用相同的代码,相同的文件在 API 级别 25 的 android 上下载,但在 API 级别以下时未下载。还有 connection.getContentLength();总是给 311 价值。我没有得到任何答案来解决这个问题。我特此添加我的代码。
我的 class 文件代码是
String HomeScreenResourcefilename = WebHomescreenResObj.getString("FileName");
int ProductTargetID = WebHomescreenResObj.getInt("ProductTargetID");
String WebURL_Part1 = context.getResources().getString(R.string.FileDownloadRootPath)+"/ExhibitorData/";
String WebURL_Part2 = GlobalVariables.tradeShowName+" - "+GlobalVariables.exhibitorName+"/HTMLHomeScreen/"+ProductTargetID +"/"+HomeScreenResourcefilename;
String WebURL = WebURL_Part1 + WebURL_Part2;
try {
URL url = new URL(WebURL);
File file = new File(context.getFilesDir(), HomeScreenResourcefilename);
URLConnection connection = url.openConnection();
connection.connect();
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e1) {
e1.printStackTrace();
LogE("error in 14 :"+e1);
}
使用 HttpURLConnection,然后使用 connection.getResponseCode() 获取状态代码。如果大于400,可能就是这个原因。
更新:使用 url 编码。
我正在使用 URLConnection 从服务器下载 HTML 文件,但出现 FileNotFoundException。我的路径是正确的。使用相同的代码,相同的文件在 API 级别 25 的 android 上下载,但在 API 级别以下时未下载。还有 connection.getContentLength();总是给 311 价值。我没有得到任何答案来解决这个问题。我特此添加我的代码。
我的 class 文件代码是
String HomeScreenResourcefilename = WebHomescreenResObj.getString("FileName");
int ProductTargetID = WebHomescreenResObj.getInt("ProductTargetID");
String WebURL_Part1 = context.getResources().getString(R.string.FileDownloadRootPath)+"/ExhibitorData/";
String WebURL_Part2 = GlobalVariables.tradeShowName+" - "+GlobalVariables.exhibitorName+"/HTMLHomeScreen/"+ProductTargetID +"/"+HomeScreenResourcefilename;
String WebURL = WebURL_Part1 + WebURL_Part2;
try {
URL url = new URL(WebURL);
File file = new File(context.getFilesDir(), HomeScreenResourcefilename);
URLConnection connection = url.openConnection();
connection.connect();
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e1) {
e1.printStackTrace();
LogE("error in 14 :"+e1);
}
使用 HttpURLConnection,然后使用 connection.getResponseCode() 获取状态代码。如果大于400,可能就是这个原因。
更新:使用 url 编码。