2013-05-06 61 views
0

我想在android上載多部分數據,但我的代碼不工作。我的代碼如下。我的上傳信息大多是文本字段。所以我保留了一個HashMap,以便該鍵將包含字段名稱,並且該值將包含字段值。但我的解決方案不起作用。請有人專注於我在這裏做錯了什麼。Android中的多部分數據上傳不起作用

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(); 
      } 
     } 
    } 
} 
+1

過去1個月,我發佈了3個問題,得到0個答案。我不明白爲什麼人們不回答我的問題。因爲我有'0'的聲望? – azizulhakim 2013-05-07 06:16:22

回答

0

我可以發送一張圖片。但是,當我想要發送文本字段值和圖像時,就會產生問題。我的帖子請求如下 -

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

IMAGE DATA GOES HERE 

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

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

LOCATION GOES HERE 

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