首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >HttpURLConnection!Connection.getInputStream为java.io.FileNotFoundException

HttpURLConnection!Connection.getInputStream为java.io.FileNotFoundException
EN

Stack Overflow用户
提问于 2014-06-12 11:11:55
回答 2查看 11.6K关注 0票数 2

我创建了一个方法"UPLPAD2“来上传文件到服务器。将我的文件分割成数据包(10MB)。还可以(100%)。但是当我调用getInputStream时,我得到的是FileNotFoundException。我想,在循环中,我创建了新的HttpURLConnection来设置"setRequestProperty“。这是一个问题。下面是我的代码:

代码语言:javascript
运行
复制
@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();
    }
}

和Logcat

代码语言:javascript
运行
复制
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$7$1.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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-06-12 11:30:10

确保您用来打开连接的URL实际存在。这可能是因为URL中的某些拼写错误或类似的原因。

票数 0
EN

Stack Overflow用户

发布于 2014-06-12 11:21:15

FileNotFoundExceptionHttpURLConnection.getInputStream()给你一个HTTP404状态的方式,所以你发送的URL不存在,如果你得到的响应码不是200,你就不应该调用getInputStream(),你应该调用getErrorStream().

但是你不需要所有这些代码。Java将为您设置content-length,您的复制循环只需如下所示:

代码语言:javascript
运行
复制
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

其中,countintbuffer是大于零的任意大小的byte[],通常为8192。您不必担心使其与文件或块大小相同,或者其他任何东西。只需设置分块传输模式,Java就会解决这个问题。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24175896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档