android - 如何将多部分表单数据和图像上传到android中的服务器?

标签 android http-post multipartform-data

在android代码中将多部分实体图像上传到服务器期间的状态代码500

HTML 格式: (可以成功添加图片到服务器)

 <form method="post" action="http://xyz/upload_picture" enctype="multipart/form-data">

      Sample Picture Upload Form Submit

      <br/><br/>

      API key: <input type="text" name="key" value="abc"><br/><br/>
      Login: <input type="text" name="login" value="text"><br/>
      Password: <input type="password" name="password" value="text"><br/><br/>

      Property ID:<input type="text" name="property_id" value="111"><br/>
      Picture File:<input type="file" name="picture"><br/><br/>

      <br/><br/>
      <input type="submit" name="" value="Upload Picture"><br/>

    </form>

安卓代码: (给出状态码 500)

   HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://xyz/upload_picture");

            try {
                MultipartEntity entity = new MultipartEntity();

                entity.addPart("key", new StringBody("abc"));
                entity.addPart("login", new StringBody("abc"));
                entity.addPart("password", new StringBody("test"));
                entity.addPart("property_id", new StringBody("111"));


                File file = new File(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_DCIM).toString()
                        + "/Camera/Test.jpg");
                entity.addPart("picture", new FileBody(file));

                httppost.setEntity(entity);
                HttpResponse response = httpclient.execute(httppost);

                Log.e("test", "SC:" + response.getStatusLine().getStatusCode());

                HttpEntity resEntity = response.getEntity();

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

                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }
                Log.e("test", "Response: " + s);
} catch (ClientProtocolException e) {
        } catch (IOException e) {
        }

最佳答案

如果像我一样,您正在为分段上传而苦苦挣扎。这是一个使用 this 中 95% 代码的解决方案安卓 fragment 。

public String multipartRequest(String urlTo, Map<String, String> parmas, String filepath, String filefield, String fileMimeType) throws CustomException {
        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;

        try {
            File file = new File(filepath);
            FileInputStream fileInputStream = new FileInputStream(file);

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

            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            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);

            outputStream = new DataOutputStream(connection.getOutputStream());
            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);
            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);

            // 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);


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

            inputStream = connection.getInputStream();

            result = this.convertStreamToString(inputStream);

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

            return result;
        } catch (Exception e) {
            logger.error(e);
            throw new CustomException(e);
        }

    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

调用代码:

//setup params
Map<String, String> params = new HashMap<String, String>(2);
        params.put("foo", hash);
        params.put("bar", caption);

String result = multipartRequest(URL_UPLOAD_VIDEO, params, pathToVideoFile, "video", "video/mp4");
//next parse result string

关于android - 如何将多部分表单数据和图像上传到android中的服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19026256/

相关文章:

android - 是否可以使用 Retrofit 通过 Multipart 发送 String[]?

asp.net-core - ASP.NET CORE "BadHttpRequestException: Unexpected end of request content."导致 future 连接卡住

ios - 在 iOS 中,如何读取源自 WKWebView 的 NSURLRequest 中的多部分表单数据?

android - 如何确定 Google Play 服务的版本?

java - GridView 我必须显示 3X3 矩阵如何做到这一点

html - 如何在nodejs中下载托管在http网络服务器上的文件

php - 将 JSON 数据从 Android 发布到 PHP 的正确方法

java - Android DefaultHTTPClient 在 javascript 驱动的网站上通过 Post 请求填充表单

android - 将元数据添加到 Facebook 应用邀请

android - 如何使用kotlin从android中的 Assets 文件夹复制数据库