0

我正在尝试在 android 中上传多部分数据,但我的代码不起作用。我的代码如下。我的上传信息主要是文本字段。所以我保留了一个 HashMap,这样键将包含字段名称,值将包含字段值。但我的解决方案不起作用。请有人让我关注我在这里做错了什么。

public static boolean uploadMultipartData(String urlString, HashMap<String, Object> dataMap){
    HttpURLConnection urlConnection = null;
    DataOutputStream outStream = null;
    DataInputStream inStream = null;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "---------------------------265001916915724";



    if (dataMap != null){
        try {
            StringBuffer data = new StringBuffer();
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(false);

            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);

            outStream = new DataOutputStream(urlConnection.getOutputStream());

            for (Entry<String, Object> entry : dataMap.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();

                outStream.writeBytes(twoHyphens + boundary + lineEnd);
                outStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\""
                                + lineEnd);
                outStream.writeBytes(value.toString());
                outStream.writeBytes(lineEnd);
            }
            outStream.writeBytes(twoHyphens + boundary + twoHyphens);
            outStream.flush();
        } 
        catch (MalformedURLException e) {
            Log.e("DEBUG", "[MalformedURLException while sending data]");
        } 
        catch (IOException e) {
            Log.e("DEBUG", "[IOException while sending data]");
        }
        finally{
            try {                   
                outStream.close();
                urlConnection.disconnect();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
4

1 回答 1

0

我可以发送单个图像。但是,当我想将文本字段值与图像一起发送时,就会产生问题。我的发帖要求如下——

-----------------------------265001916915724
Content-Disposition: form-data; name="file"

IMAGE DATA GOES HERE

-----------------------------265001916915724

Content-Disposition: form-data; name="location"

LOCATION GOES HERE

-----------------------------265001916915724--
于 2013-05-07T15:23:19.537 回答