【问题标题】:Multipart, set Content-Type of one partMultipart,设置一个部分的Content-Type
【发布时间】:2012-11-13 16:13:12
【问题描述】:

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

// 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”,服务器仅接受该文件,但仅适用于图像。用户名和密码必须是纯文本。这可能吗?

【问题讨论】:

    标签: java android content-type multipart


    【解决方案1】:

    这将起作用:

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

    别忘了检查你的文件是否存在!

    【讨论】:

      【解决方案2】:

      StringBody 有一个接受内容类型的构造函数:

      new StringBody(titleString, "application/atom+xml", Charset.forName("UTF-8"));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-27
        • 2021-08-28
        • 1970-01-01
        • 2018-01-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多