我第一次使用HttpURLConnection进行了第一次测试。现在我也想支持https,但它不起作用。我整天都在这里,到目前为止一切都没有。过去的大多数问题都与证书问题有关。奇怪的是,在我的情况下,它下载文件,但它已损坏(如果它是一个简单的文件),或拉链内容丢失(空)。我会发布我的代码,看看我是否做错了。
try{
URL url = new URL(stuffs[0]);//<-actual url I am searching https://...
String fileName = stuffs[1];
String optionalFilePath = stuffs[2] == null ? null : stuffs[2];
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(20000);
connection.connect();
if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
checkErrorCode(connection.getResponseCode());
return false;
}
InputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream out = null;
if(optionalFilePath == null)
out = new FileOutputStream(PATH +"/"+fileName);
else {
File newDir = new File(PATH+optionalFilePath);
newDir.mkdirs();
out = new FileOutputStream(PATH + (optionalFilePath==null?"":optionalFilePath) +"/"+fileName);
}
byte[] buffer = new byte[1024];
int count;
while((count = in.read(buffer)) != -1){
out.write(buffer, 0, count);
}
out.flush();
out.close();
in.close();
}
经过进一步调试,我发现内容长度为-1。所以我觉得拉链是空的是有道理的。现在我不太清楚它为什么返回-1。我正确地在网络浏览器上下载它。所以我知道它存在。
答案 0 :(得分:0)
通过https下载文件您应该接受来自应用程序Trusting all certificates using HttpClient over HTTPS的https证书 并https file download in android causing exception
对于Downlod zip或任何检查 Download a file with Android, and showing the progress in a ProgressDialog
答案 1 :(得分:0)
我相信答案是你正在调用connect()。
URL url = new URL(stuffs[0]);//<-actual url I am searching https://...
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(20000);
connection.connect();
if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
checkErrorCode(connection.getResponseCode());
return false;
}
InputStream in = new BufferedInputStream(connection.getInputStream());
请勿调用connection.connect
,并在调用connection.getInputStream()
的行后移动响应代码检查。