How to upload file with other string data using HttpURLConnection in android?

柔情痞子 提交于 2020-01-04 04:32:07

问题


I want to upload file with other string data to the server in one request using HttpURLConnection (not using MultiPartEntityBuilder)...Currently I can send the file but not the other string data with it !! Here is my current code for sending the file to server :

    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection connection = null;
    String fileName = sourceFile.getName();

    try {
        connection = (HttpURLConnection) new URL(FILE_UPLOAD_URL).openConnection();
        connection.setRequestMethod("POST");
        String boundary = "---------------------------boundary";
        String tail = "\r\n--" + boundary + "--\r\n";
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        connection.setRequestProperty("token", sharedpreferences.getString("token", ""));
        connection.setRequestProperty("app_version", app_version);
        connection.setRequestProperty("api_version", api_version);
        connection.setDoOutput(true);

        String metadataPart = "--"
                + boundary
                + "\r\n"
                + "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
                + ""
                + "\r\n";

        String fileHeader1 = "--"
                + boundary
                + "\r\n"
                + "Content-Disposition: form-data; name=\"myFile\"; filename=\""
                + fileName
                + "\"\r\n"
                + "Content-Type: application/octet-stream\r\n"
                + "Content-Transfer-Encoding: binary\r\n";

        long fileLength = sourceFile.length() + tail.length();
        String fileHeader2 = "Content-length: " + fileLength + "\r\n";
        String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
        String stringData = metadataPart + fileHeader;

        long requestLength = stringData.length() + fileLength;
        connection.setRequestProperty("Content-length", "" + requestLength);
        connection.setFixedLengthStreamingMode((int) requestLength);
        connection.connect();

        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes(stringData);
        out.flush();

        int progress = 0;
        int bytesRead;
        byte buf[] = new byte[1024];
        BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(sourceFile));
        while ((bytesRead = bufInput.read(buf)) != -1) {
            // write output
            out.write(buf, 0, bytesRead);
            out.flush();
            progress += bytesRead; // Here progress is total uploaded bytes

            publishProgress((int) ((progress * 100) / sourceFile.length())); // sending progress percent to publishProgress
        }

        // Write closing boundary and close stream
        out.writeBytes(tail);
        out.flush();
        out.close();

        // Get server response
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder builder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

    } catch (Exception e) {
        // Exception
    } finally {
        if (connection != null) connection.disconnect();
    }
    return null;

Any help would be appreciated !!Thank you...

来源:https://stackoverflow.com/questions/44852746/how-to-upload-file-with-other-string-data-using-httpurlconnection-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!