java - Multipart,设置一个部分的Content-Type

标签 java android content-type multipart

我有这段代码可以将数据发布到我的服务器:

// HTTP Settings
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(
                    "http://myserver.com/Login");
            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            // Http Headers
            postRequest.addHeader("Accept", "application/xml");
            postRequest.addHeader("Connection", "keep-alive");

            // Credentials
            reqEntity.addPart("username", new StringBody(ServerData.username));
            reqEntity.addPart("password", new StringBody(ServerData.password));

            if (m_sigFile.exists()) {
                Bitmap m_sig = BitmapFactory.decodeFile(sigFilePath
                        + "m_sig.jpg");
                ByteArrayOutputStream m_bao = new ByteArrayOutputStream();
                m_sig.compress(Bitmap.CompressFormat.JPEG, 90, m_bao);

                byte[] m_ba = m_bao.toByteArray();
                String m_ba1 = Base64.encodeToString(m_ba, 0);
                reqEntity.addPart("m_sig.jpg", new StringBody(m_ba1));
            }

            postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            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);
            }

代码运行完美,除了 jpeg 文件外,所有数据都发送到服务器。如果我将内容类型设置为“图像/jpeg”,服务器仅接受该文件,但仅限于图像。用户名和密码必须是纯文本。这可能吗?

最佳答案

这会起作用:

            ContentBody cbFile = new FileBody(new File(myPath
                    + "image_1.jpg"),
                    "image/jpeg");
            reqEntity.addPart("photo1"), cbFile);

不要忘记检查您的文件是否存在!

关于java - Multipart,设置一个部分的Content-Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13560546/

相关文章:

javascript - 将内容类型设置为 application/json 时出现意外 token 错误

android - 滑动菜单 : Showing seconday menu on an event

android - 我可以加快 Admob 在 Android 上的加载速度吗?

java - 改进第10001个素数项目

java - 为什么启动程序3次后才出现JTextfield和JButton?

android - 使用 Android Studio 创建新的空白 Activity

google-chrome - 强制 Chrome 根据 Content-Type header 打开某些 URL

Apache2 未在 header 中发送 "Content-Type"

java - 没有类爆炸的选择性组合的良好对象结构

java - 用泛型克隆