Android HTTP POST文件上载无法使用HttpUrlConnection

Android HTTP POST文件上载无法使用HttpUrlConnection,android,http-post,out-of-memory,httpurlconnection,Android,Http Post,Out Of Memory,Httpurlconnection,我正试图通过HTTP POST从我的设备将文件上载到服务器。我有两种方法upload1和upload2 Upload1使用HttpPost类,它可以工作,但对于较大的文件,它会抛出内存异常 Upload2使用HttpURLConnection,但它不起作用。(我从服务器收到错误的请求消息。)我希望upload2正常工作,因为它使用流发送数据,并且不会抛出内存不足异常。 我查看了wireshark中的包,标题似乎是相同的,但是upload1的长度是380,upload2的长度只有94。有什么问题吗

我正试图通过HTTP POST从我的设备将文件上载到服务器。我有两种方法upload1和upload2

Upload1使用HttpPost类,它可以工作,但对于较大的文件,它会抛出内存异常

Upload2使用HttpURLConnection,但它不起作用。(我从服务器收到错误的请求消息。)我希望upload2正常工作,因为它使用流发送数据,并且不会抛出内存不足异常。 我查看了wireshark中的包,标题似乎是相同的,但是upload1的长度是380,upload2的长度只有94。有什么问题吗

private void upload1(File file) {

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url + "?recname="
                    + fileName);

            // ///////////////////////////////////////
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "---------------------------This is the boundary";

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);

            FileInputStream fin = new FileInputStream(file);

            byte audioData[] = new byte[(int) file.length()];

            fin.read(audioData);
            fin.close();

            // Send a binary file
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
                    + fileName + "\"" + lineEnd);
            dos.writeBytes("Content-Type: audio/mp4" + lineEnd);
            dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
            dos.writeBytes(lineEnd);
            dos.write(audioData);
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            dos.flush();
            dos.close();

            ByteArrayInputStream content = new ByteArrayInputStream(
                    baos.toByteArray());
            BasicHttpEntity entity = new BasicHttpEntity();
            entity.setContent(content);

            entity.setContentLength(baos.toByteArray().length);

            httppost.addHeader("Content-Type", "multipart/form-data; boundary="
                    + boundary);

            httppost.setEntity(entity);

            // //////////////////////////////////

            HttpResponse response = httpclient.execute(httppost);

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent(), "UTF-8"));
            StringBuilder builder = new StringBuilder();

            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }

            reader.close();
            message = builder.toString();
            System.out.println(message);

        } catch (UnknownHostException e) {
            message = "Error! Server is unreachable. Check you internet connection!";
        } catch (Exception e) {
            message = "error: " + e.toString();
        }

    }
/////////////////////////////////////////////////////////////////////////////////////////

private void upload2(File file) {

        HttpURLConnection connection = null;

        String pathToOurFile = file.getPath();
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "---------------------------This is the boundary";

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

        try {

            fileInputStream = new FileInputStream(new File(pathToOurFile));

            URL server_url = new URL(url+ "?recname="
                    + fileName);
            connection = (HttpURLConnection) server_url.openConnection();

            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            // Enable POST method
            connection.setRequestMethod("POST");

            String bodyHeader = twoHyphens
                    + boundary
                    + lineEnd
                    + "Content-Disposition: form-data; name=\"file\";filename=\""
                    + fileName + "\"" + lineEnd + "Content-Type: audio/mp4"
                    + lineEnd + "Content-Transfer-Encoding: binary" + lineEnd
                    + lineEnd + twoHyphens + boundary + twoHyphens ;

            byte[] bodyHeaderAray = bodyHeader.getBytes();

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("Expect", "100-continue");

            // Content-Length
            int bodyHeaderSize = (int) file.length() + bodyHeaderAray.length;
            System.out.println("body header size: " + bodyHeaderSize);
            // connection.setFixedLengthStreamingMode(bodyHeaderSize);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream
                    .writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
                            + fileName + "\"");
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes("Content-Type: audio/mp4" + lineEnd);
            outputStream.writeBytes("Content-Transfer-Encoding: binary"
                    + lineEnd);

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

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            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);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                    + lineEnd);

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            message = serverResponseMessage;

        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

根据你上传文件时遇到的问题。您应该使用多部分机制将文件上载到服务器

    httpclient-4.1.jar
    httpcore-4.1.jar
    httpmime-4.1.jar
    apache-mime4j-0.6.1.jar
为此,您需要在项目中添加几个库,并将其用于HTTP连接和文件数据

    private boolean uploadFile(File mFile) {
            boolean success = true;
            String filename = mFile.getName();
            MultipartEntity data_to_send = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            try {
                data_to_send.addPart(
                        "name",
                        new StringBody(
                                filename.substring(filename.lastIndexOf("/") + 1)));
                data_to_send.addPart("fileData", new FileBody(mFile));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            try {
                String responseData = ConsumeWebService.sendRequest(data_to_send,
                        Global.BASE_URL + serviceUrl);
                if (TextUtils.isEmpty(responseData)
                        || responseData.equals(ConsumeWebService.ERROR_CODE)) {
                    success = false;
                }
            } catch (Exception e) {
                success = false;
                e.printStackTrace();
            }
            return success;
        }


public static String sendRequest(MultipartEntity data, String url) {
        String response = "";
        response = postData(url, data);
        return response;
    }


private static String postData(String url, MultipartEntity data) {
        String strResponse = "";

        try {
            Log.d(Global.TAG, "Post URL is " + url);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(data);
            strResponse = httpClient.execute(httpPost,
                    new BasicResponseHandler());
        } catch (UnsupportedEncodingException e) {
            strResponse = ERROR_CODE;
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            strResponse = ERROR_CODE;
            e.printStackTrace();
        } catch (IOException e) {
            strResponse = ERROR_CODE;
            e.printStackTrace();
        }
        return strResponse;
    }

您可以通过以下方式根据自己的POST请求进行构建

我认为在上传2中,您缺少了一个lineEnd:

....
outputStream.writeBytes("Content-Transfer-Encoding: binary"
                + lineEnd);
在此之后,您必须传输数据,并且在实际数据之前需要两个测线端,因此应为:

....
outputStream.writeBytes("Content-Transfer-Encoding: binary"
                + lineEnd + lineEnd);

对于读取文件并将其置于多部分/表单数据结构中,我建议您采用适合我的方式:

FileInputStream fileInputStream=new FileInputStream(file);
byte[] bytes= new bytes[fileInputStream.getChannel().size()];
fileInputStream.read(bytes);
fileInputStream.close();
outputStream.write(bytes);
outputStream.writeBytes(lineEnd);

希望有帮助。

我不认识这些图书馆。MultipartEntity是否负责流式传输文件?我担心这个库会再次出现内存不足的异常。你可以通过谷歌搜索下载这个库。此库功能强大,足以处理内存不足的问题。因此,不要担心partMultipartEntity目前已被弃用。Apache建议改用MultipartEntityBuilder(),但我还没有在Android上实现这一点。