HttpURLConnection的! Connection.getInputStream是java.io.FileNotFoundException

时间:2014-06-12 03:11:55

标签: java android httpurlconnection filenotfoundexception

我创建了一个方法“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();
    }
}

和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$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

2 个答案:

答案 0 :(得分:5)

FileNotFoundExceptionHttpURLConnection.getInputStream()为您提供HTTP 404状态的方式。因此,您发布的URL不存在。如果您获得的回复代码不是200,那么您根本不应该致电getInputStream(),那么您应该致电getErrorStream().

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

while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

其中countintbuffer是任意大小为零的byte[],通常为8192.您不必担心制作它与文件,块或其中任何一个大小相同。只需设置分块传输模式,Java就可以解决它。

答案 1 :(得分:0)

确保您打开连接的网址确实存在。这可能会导致URL或类似内容中出现一些拼写错误。