HttpURL连接!Connection.getInputStream 是 java.io.FileNotFoundException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24175896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HttpURLConnection! Connection.getInputStream is java.io.FileNotFoundException
提问by ThuanNgo
I created a method "UPLPAD2" to upload file to server. Splitting my file to packets(10MB). It's OK (100%). But when i call getInputStream, i get FileNotFoundException. I think, in loop, i make new HttpURLConnection to set "setRequestProperty". This is a problem. Here's my code:
我创建了一个方法“UPLPAD2”来上传文件到服务器。将我的文件拆分为数据包(10MB)。没问题(100%)。但是当我调用 getInputStream 时,我得到 FileNotFoundException。我认为,在循环中,我创建了新的 HttpURLConnection 来设置“setRequestProperty”。这是个问题。这是我的代码:
@SuppressLint("NewApi")
public int upload2(URL url, String filePath,
OnProgressUpdate progressCallBack, AtomicInteger cancelHandle)
throws IOException {
HttpURLConnection connection = null;
InputStream fileStream = null;
OutputStream out = null;
InputStream in = null;
HttpResponse response = new HttpResponse();
Log.e("Upload_Url_Util", url.getFile());
Log.e("Upload_FilePath_Util", filePath);
long total = 0;
try {
// Write the request.
// Read from filePath and upload to server (url)
byte[] buf = new byte[1024];
fileStream = new FileInputStream(filePath);
long lenghtOfFile = (new java.io.File(filePath)).length();
Log.e("LENGHT_Of_File", lenghtOfFile + "");
int totalPacket = 5 * 1024 * 1024; // 10 MB
int totalChunk = (int) ((lenghtOfFile + (totalPacket - 1)) / totalPacket);
String headerValue = "";
String contentLenght = "";
for (int i = 0; i < totalChunk; i++) {
long from = i * totalPacket;
long to = 0;
if ((from + totalPacket) > lenghtOfFile) {
to = lenghtOfFile;
} else {
to = (totalPacket * (i + 1));
}
to = to - 1;
headerValue = "bytes " + from + "-" + to + "/" + lenghtOfFile;
contentLenght = "Content-Length:" + (to - from + 1);
Log.e("Conten_LENGHT", contentLenght);
connection = client.open(url);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Range", headerValue);
connection.setRequestProperty("Content-Length",
Long.toString(to - from + 1));
out = connection.getOutputStream();
Log.e("Lenght_Of_File", lenghtOfFile + "");
Log.e("Total_Packet", totalPacket + "");
Log.e("Total_Chunk", totalChunk + "");
Log.e("Header_Valure", headerValue);
int read = 1;
while (read > 0 && cancelHandle.intValue() == 0
&& total < totalPacket * (i + 1)) {
read = fileStream.read(buf);
if (read > 0) {
out.write(buf, 0, read);
total += read;
progressCallBack
.onProgressUpdate((int) ((total * 100) / lenghtOfFile));
}
}
Log.e("TOTAL_", total + "------" + totalPacket * (i + 1));
Log.e("I_", i + "");
Log.e("LENGHT_Of_File", lenghtOfFile + "");
if (i < totalChunk - 1) {
connection.disconnect();
}
out.close();
}
// Read the response.
response.setHttpCode(connection.getResponseCode());
in = connection.getInputStream(); // I GET ERROR HERE.
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Unexpected HTTP response: "
+ connection.getResponseCode() + " "
+ connection.getResponseMessage());
}
byte[] body = readFully(in);
response.setBody(body);
response.setHeaderFields(connection.getHeaderFields());
if (cancelHandle.intValue() != 0) {
return 1;
}
JSONObject jo = new JSONObject(response.getBodyAsString());
Log.e("Upload_Body_res_", response.getBodyAsString());
if (jo.has("error")) {
if (jo.has("code")) {
int errCode = jo.getInt("code");
Log.e("Upload_Had_errcode", errCode + "");
return errCode;
} else {
return 504;
}
}
Log.e("RESPONE_BODY_UPLOAD", response.getBodyAsString() + "");
return 0;
} catch (Exception e) {
e.printStackTrace();
Log.e("Http_UpLoad_Response_Exception", e.toString());
response.setHttpCode(connection.getResponseCode());
Log.e("ErrorCode_Upload_Util_Return", response.getHttpCode() + "");
if (connection.getResponseCode() == 200) {
return 1;
} else if (connection.getResponseCode() == 0) {
return 1;
} else {
return response.getHttpCode();
}
// Log.e("ErrorCode_Upload_Util_Return", response.getHttpCode()+"");
} finally {
if (fileStream != null)
fileStream.close();
if (out != null)
out.close();
if (in != null)
in.close();
}
}
And Logcat
和 Logcat
06-12 09:39:29.558: W/System.err(30740): java.io.FileNotFoundException: http://download-f77c.fshare.vn/upload/NRHAwh+bUCxjUtcD4cn9xqkADpdL32AT9pZm7zaboHLwJHLxOPxUX9CQxOeBRgelkjeNM5XcK11M1V-x
06-12 09:39:29.558: W/System.err(30740): at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:187)
06-12 09:39:29.563: W/System.err(30740): at com.fsharemobile.client.HttpUtil.upload2(HttpUtil.java:383)
06-12 09:39:29.563: W/System.err(30740): at com.fsharemobile.fragments.ExplorerFragment.run(ExplorerFragment.java:992)
06-12 09:39:29.568: W/System.err(30740): at java.lang.Thread.run(Thread.java:856)
06-12 09:39:29.568: E/Http_UpLoad_Response_Exception(30740): java.io.FileNotFoundException: http://download-f77c.fshare.vn/upload/NRHAwh+bUCxjUtcD4cn9xqkADpdL32AT9pZm7zaboHLwJHLxOPxUX9CQxOeBRgelkjeNM5XcK11M1V-x
采纳答案by Christopher Francisco
make sure the URL you open the connection with, actually exists. It's probably cause some typo in the URL or similar.
确保您打开连接的 URL 确实存在。这可能是因为 URL 或类似内容中出现了一些拼写错误。
回答by user207421
FileNotFoundException
is HttpURLConnection.getInputStream()
's way of giving you an HTTP 404 status. So the URL you are POST-ing to doesn't exist. If the response code you get isn't 200 you shouldn't call getInputStream()
at all, you should call getErrorStream().
FileNotFoundException
isHttpURLConnection.getInputStream()
为您提供 HTTP 404 状态的方式。所以你要发布的 URL 不存在。如果你得到的响应代码不是 200 你根本不getInputStream()
应该打电话,你应该打电话getErrorStream().
But you don't need all this code. Java will set the content-length for you, and your copy loop only needs to look like this:
但是您不需要所有这些代码。Java 将为您设置内容长度,您的复制循环只需如下所示:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
where count
is an int
and buffer
is a byte[]
of any size greater than zero, typically 8192. You don't have to worry about making it the same size as the file, or chunks, or any of that. Just set chunked transfer mode, and Java will figure it out.
其中count
是int
和buffer
是byte[]
大于零的任意大小,通常为 8192。您不必担心使其与文件或块或任何其他大小相同。只需设置分块传输模式,Java 就会搞定。