【问题标题】:Sending image with parameters in httpurl在 httpurl 中发送带有参数的图像
【发布时间】:2017-03-28 22:52:19
【问题描述】:

这是我用来附加图像参数的代码:

  DataOutputStream request = new DataOutputStream(
                        con.getOutputStream());
                if(bitmap!=null)
                {
                    request.writeBytes(twoHyphens + boundary + crlf);

                    request.writeBytes("Content-Disposition: form-data; name=\"profile_picture\";filename=\"profile_picture.jpg\"" + crlf);

                    request.writeBytes("Content-Type: image/jpeg" + crlf);
                    request.writeBytes(crlf);
                    byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
                    for (int i = 0; i < bitmap.getWidth(); ++i) {
                        for (int j = 0; j < bitmap.getHeight(); ++j) {
                            //we're interested only in the MSB of the first byte,
                            //since the other 3 bytes are identical for B&W images
                            pixels[i + j] = (byte) ((bitmap.getPixel(i, j) & 0x80) >> 7);
                        }
                    }

                    request.write(pixels);//your image array here buddy
                    request.writeBytes(crlf);
                    request.writeBytes(twoHyphens + boundary + crlf);


                    request.writeBytes(twoHyphens + boundary + crlf);
                    Set<Map.Entry<String, Object>> set=params.valueSet();
                    Iterator itr = set.iterator();

                    while (itr.hasNext()) {
                        Map.Entry me = (Map.Entry)itr.next();

                        request.writeBytes("Content-Disposition: form-data; name=\""+me.getKey().toString()+"\"" + crlf);
                        request.writeBytes(crlf);
                        request.writeBytes(me.getValue().toString());//your parameter value
                        request.writeBytes(crlf);
                        request.writeBytes(twoHyphens + boundary +
                                crlf);
                    }


                    request.flush();
                    request.close();


                }

我指的是this

如果我不发送图像,那么这些值会完美地发送到服务器,如果我添加图像,那么我会发现文本参数无法发送。

【问题讨论】:

    标签: android httpurlconnection


    【解决方案1】:

    为此,您需要使用MultipartEntity。有了这个,你可以发送多部分请求。

    【讨论】:

    • MultipartEntity 已弃用,那是我没有使用它。
    • 从文档中,您会注意到您应该使用 MultipartEntityBuilder 作为替代方案。
    • 最后我们必须将 HttpClient 与 multipartentitybuilder 一起使用,这已被弃用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    相关资源
    最近更新 更多