使用多部分帖子向服务器发布发布数据

时间:2014-01-03 22:19:26

标签: android http-post multipartform-data

我在谷歌搜索了许多关于向服务器发布数据的多部分技术的博客,每个人都在做与我正在做的相同的方式,但我仍然无法将我的参数发布到服务器以及图像这里是我的代码:

HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);

            byte[] imageByte = null;
            ByteArrayBody bab =  null;
            if(order.getSignature() != null)
            {
                imageByte = order.getSignature();
                httppost.setHeader("Content-Type", "image/png");
                bab = new ByteArrayBody(imageByte, "signature.png");
            }

MultipartEntityBuilder builder = MultipartEntityBuilder.create();        
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            Charset chars = Charset.forName("UTF-8");
            builder.setCharset(chars);

            builder.addTextBody("SessId",sessionid);  
            builder.addTextBody("Status",order.getDeliveryStatus());
            builder.addTextBody("Notes",order.getNotes());
            builder.addTextBody("OrderId",order.getId());
            if(order.getConfirm_delivery_datetime() != null)
            builder.addTextBody("ConfirmDeliveryDate",order.getConfirm_delivery_datetime());
            if(bab != null)
            builder.addPart("Signature",  bab);
            final HttpEntity yourEntity = builder.build();
httppost.setEntity(yourEntity);


            HttpResponse response = httpclient.execute(httppost);

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                  s = new StringBuilder();
                  s.append("Error:" + response.getStatusLine().getStatusCode());
           }else {
// i get success but no data transfers on server.

}

是的,当我使用NameValuePair技术时,我确实收到了服务器上的所有参数,任何人都指导我在上面的代码中做了什么错误?

ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

               nameValuePair.add(new BasicNameValuePair("SessId",sessionid));
               nameValuePair.add(new BasicNameValuePair("Status",order.getDeliveryStatus()));
               nameValuePair.add(new BasicNameValuePair("Notes",order.getNotes()));
               nameValuePair.add(new BasicNameValuePair("OrderId",order.getId()));
               nameValuePair.add(new BasicNameValuePair("ConfirmDeliveryDate",order.getConfirm_delivery_datetime()));

                   httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

我花了两天时间讨论这个问题但我无法使用我的项目中包含的apache .jar文件通过multipart发布数据,因为该技术已在上述问题中发布。

然后我不得不改变以纯java方式发布的方式,并在下面给出了work.code:

自定义类使用率:

 try {
                MultipartUtil multipart = new MultipartUtil(requestURL, charset);

                multipart.addHeaderField("User-Agent", "CodeJava");

                multipart.addFormField("SessId", sessionid);
                multipart.addFormField("Status", order.getDeliveryStatus());
                multipart.addFormField("Notes",order.getNotes());
                multipart.addFormField("OrderId", order.getId());
                if(order.getConfirm_delivery_datetime() != null)
                multipart.addFormField("ConfirmDeliveryDate", order.getConfirm_delivery_datetime());

                if(order.getSignature() != null)
                multipart.addPart("Signature", order.getSignature(),"Signature"+order.getId()+".png");

                List<String> response = multipart.finish();

                System.out.println("SERVER REPLIED:");

                for (String line : response) {
                    System.out.println(line);
                }
            } catch (IOException ex) {
                System.err.println(ex);

            }

自定义类:

package com.utils;

import java.io.BufferedReader;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import android.os.Build;

/**
 * This utility class provides an abstraction layer for sending multipart HTTP
 * POST requests to a web server.
 * @author www.codejava.net
 *
 */

    public class MultipartUtil {
        private final String boundary;
        private static final String LINE_FEED = "\r\n";
        private HttpURLConnection httpConn;
        private String charset;
        private OutputStream outputStream;
        private PrintWriter writer;

        /**
         * This constructor initializes a new HTTP POST request with content type
         * is set to multipart/form-data
         * @param requestURL
         * @param charset
         * @throws IOException
         */
        public MultipartUtil(String requestURL, String charset)
                throws IOException {
            this.charset = charset;

            // creates a unique boundary based on time stamp
            boundary = "===" + System.currentTimeMillis() + "===";

            URL url = new URL(requestURL);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setUseCaches(false);
            httpConn.setDoOutput(true); // indicates POST method
            httpConn.setDoInput(true);
            httpConn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + boundary);
            httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
            httpConn.setRequestProperty("Test", "Bonjour");
            outputStream = httpConn.getOutputStream();
            writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                    true);
        }

        /**
         * Adds a form field to the request
         * @param name field name
         * @param value field value
         */
        public void addFormField(String name, String value) {
            writer.append("--" + boundary).append(LINE_FEED);
            writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
                    .append(LINE_FEED);
            writer.append("Content-Type: text/plain; charset=" + charset).append(
                    LINE_FEED);
            writer.append(LINE_FEED);
            writer.append(value).append(LINE_FEED);
            writer.flush();
        }

        /**
         * Adds a upload file section to the request
         * @param fieldName name attribute in <input type="file" name="..." />
         * @param uploadFile a File to be uploaded
         * @throws IOException
         */
        public void addFilePart(String fieldName, File uploadFile)
                throws IOException {
            String fileName = uploadFile.getName();
            writer.append("--" + boundary).append(LINE_FEED);
            writer.append(
                    "Content-Disposition: form-data; name=\"" + fieldName
                            + "\"; filename=\"" + fileName + "\"")
                    .append(LINE_FEED);
            writer.append(
                    "Content-Type: "
                            + URLConnection.guessContentTypeFromName(fileName))
                    .append(LINE_FEED);
            writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
            writer.append(LINE_FEED);
            writer.flush();

            FileInputStream inputStream = new FileInputStream(uploadFile);
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
            inputStream.close();

            writer.append(LINE_FEED);
            writer.flush();    
        }


        public void addPart(String fieldName, byte[] uploadFile,String filename)
                throws IOException {
            String fileName = filename;
            writer.append("--" + boundary).append(LINE_FEED);
            writer.append(
                    "Content-Disposition: form-data; name=\"" + fieldName
                            + "\"; filename=\"" + fileName + "\"")
                    .append(LINE_FEED);
            writer.append(
                    "Content-Type: "
                            + URLConnection.guessContentTypeFromName(fileName))
                    .append(LINE_FEED);
            writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
            writer.append(LINE_FEED);
            writer.flush();

            ByteArrayOutputStream baos = new ByteArrayOutputStream(uploadFile.length);
            baos.write(uploadFile, 0, uploadFile.length);
            InputStream inputStream = new ByteArrayInputStream(baos.toByteArray()); 
            //InputStream inputStream = new Byte(uploadFile);
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
            inputStream.close();

            writer.append(LINE_FEED);
            writer.flush();    
        }

        /**
         * Adds a header field to the request.
         * @param name - name of the header field
         * @param value - value of the header field
         */
        public void addHeaderField(String name, String value) {
            writer.append(name + ": " + value).append(LINE_FEED);
            writer.flush();
        }

        /**
         * Completes the request and receives response from the server.
         * @return a list of Strings as response in case the server returned
         * status OK, otherwise an exception is thrown.
         * @throws IOException
         */
        public List<String> finish() throws IOException {
            List<String> response = new ArrayList<String>();

            writer.append(LINE_FEED).flush();
            writer.append("--" + boundary + "--").append(LINE_FEED);
            writer.close();

            // checks server's status code first
            int status = httpConn.getResponseCode();
            if (status == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        httpConn.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    response.add(line);
                }
                reader.close();
                httpConn.disconnect();
            } else {
                if (Build.VERSION.SDK_INT > 13) { httpConn.setRequestProperty("Connection", "close"); }
                throw new IOException("Server returned non-OK status: " + status);
            }

            return response;
        }
    }

答案 1 :(得分:-1)

我使用apache http库发送带有post的图像的解决方案:

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] imageBytes = baos.toByteArray();

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(StaticData.AMBAJE_SERVER_URL + StaticData.AMBAJE_ADD_AMBAJ_TO_GROUP);

            String boundary = "-------------" + System.currentTimeMillis();

            httpPost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);

            ByteArrayBody bab = new ByteArrayBody(imageBytes, "pic.png");
            StringBody sbOwner = new StringBody(StaticData.loggedUserId, ContentType.TEXT_PLAIN);
            StringBody sbGroup = new StringBody("group", ContentType.TEXT_PLAIN);

            HttpEntity entity = MultipartEntityBuilder.create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .setBoundary(boundary)
                    .addPart("group", sbGroup)
                    .addPart("owner", sbOwner)
                    .addPart("image", bab)
                    .build();

            httpPost.setEntity(entity);

            try {
                HttpResponse response = httpclient.execute(httpPost);
                ...then reading response