簡體   English   中英

Multipart,設置一部分的 Content-Type

[英]Multipart, set Content-Type of one part

我有這個代碼將數據發布到我的服務器:

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

不要忘記檢查您的文件是否存在!

StringBody有一個接受內容類型的構造函數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM