简体   繁体   中英

Multipart, set Content-Type of one part

I have this code to post data to my server:

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

The code works perfectly, all data is send to the server except for the jpeg file. The server only accepts the file if I set the content type to 'image/jpeg', but only for the image. The username and password has to be in plain text. Is this possible?

This will work:

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

Don't forget to check if you file exists!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM