使用httpurlconnection发送文件时出现FileNotFound异常

时间:2019-04-08 11:33:18

标签: java android http httpurlconnection

我需要将包含数据和文件的请求发送到服务器。当我只是尝试发送数据时,它可以工作,但是如果我也包含文件的代码,即使我可以清楚地看到从文件中读取的字节数,我也会收到FileNotFoundException。

我试图设置更大的连接超时,但是似乎没有任何作用。

这是应该发送数据的功能:

public String multipartRequest(String urlTo, Map<String, String> parmas, String filepath, String filefield) throws Exception {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        InputStream inputStream = null;

        String twoHyphens = "--";
        String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
        String lineEnd = "\r\n";

        String result = "";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;

        String[] q = filepath.split("/");
        int idx = q.length - 1;
        Log.e("ceva", q[idx]);

        try {

            URL url = new URL(urlTo);
            connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            connection.setRequestProperty("Accept", "application/json");


            outputStream = new DataOutputStream(connection.getOutputStream());
            if (!filepath.equals(""))
            {
                if(Build.VERSION.SDK_INT>22){
                    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
                    requestPermissions(permissions,1);
                }
                File file = new File(filepath);
                FileInputStream fileInputStream = new FileInputStream(file);

                InputStream is = new BufferedInputStream(fileInputStream);
                String fileMimeType = URLConnection.guessContentTypeFromStream(is);

                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
                outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd);
                outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);

                outputStream.writeBytes(lineEnd);

                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                Log.e("baiti", Integer.toString(bytesRead));
                while (bytesRead > 0) {
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }

                outputStream.writeBytes(lineEnd);
                //fileInputStream.close();
            }


            // Upload POST Data
            Iterator<String> keys = parmas.keySet().iterator();
            while (keys.hasNext()) {
                String key = keys.next();
                String value = parmas.get(key);

                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
                outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(value);
                outputStream.writeBytes(lineEnd);
            }

            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            Log.e("something", "At least I got here");

            if (200 != connection.getResponseCode()) {
                //throw new Exception("Failed to upload code:" + connection.getInputStream() + " " + connection.getResponseMessage() + " "  + connection.getContent());
            }

            inputStream = connection.getInputStream();

            result = this.convertStreamToString(inputStream);

            inputStream.close();
            outputStream.flush();
            outputStream.close();

            return result;
        } catch (Exception e) {
            Log.e("cam asta e", e.toString());
            inputStream = connection.getInputStream();

            return this.convertStreamToString(inputStream);
        }

    }

我希望得到一个200代码和一个json作为答案,但是我会得到422和FileNotFoundException,即使“至少我到这里”行似乎在我放置的任何地方都执行了,所以代码没有不会立即到达catch块。

0 个答案:

没有答案