使用httpurl中的参数发送图像

时间:2016-11-15 06:24:02

标签: android httpurlconnection

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

  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

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

1 个答案:

答案 0 :(得分:0)

为此您需要使用MultipartEntity。有了它,您可以在请求中发送multipart。