2014-06-16 163 views
11

我嘗試上傳數據到服務器,我的數據包含多個圖像和大JSON,在它之前,我嘗試發送圖像轉換爲字符串使用base64併發送我的另一個數據和圖像我之前已經轉換JSON,但我在這裏面臨問題OutOfMemory,所以我閱讀其中一個解決方案,說我必須嘗試使用​​MultipartEntityBuilder。 我仍然困惑,不明白如何做到這一點MultiPartEntityBuilder,有沒有人可以幫助我做到這一點與MultiPartEntityBuilder?這是我的代碼:Android:上傳圖片和JSON使用MultiPartEntityBuilder

try{ 
    //membuat HttpClient 
    //membuat HttpPost 
    HttpPost httpPost= new HttpPost(url); 
    SONObject jsonObjectDP= new JSONObject(); 
    System.out.println("file audio "+me.getModelDokumenPendukung().getAudio()); 
    jsonObjectDP.put("audio_dp",MethodEncode.EncodeAudio(me.getModelDokumenPendukung().getAudio())); 
    jsonObjectDP.put("judul_audio",me.getModelDokumenPendukung().getJudul_audio()); 
    jsonObjectDP.put("ket_audio",me.getModelDokumenPendukung().getKet_audio()); 
    JSONArray ArrayFoto= new JSONArray(); 

    //This loop For my multiple File Images 
    List<ModelFoto>ListFoto=me.getModelDokumenPendukung().getListFoto(); 
    for (int i=0; i<ListFoto.size();i++) { 
     JSONObject jsonObject= new JSONObject(); 
     jsonObject.put("foto", ListFoto.get(i).getFile_foto()); 
     jsonObject.put("judul_foto", ListFoto.get(i).getJudul_foto()); 
     jsonObject.put("ket_foto", ListFoto.get(i).getKet_foto()); 
     ArrayFoto.put(jsonObject); 

    } 

    JSONObject JSONESPAJ=null; 
    JSONESPAJ = new JSONObject(); 
    JSONObject JSONFINAL = new JSONObject(); 
      JSONESPAJ.put("NO_PROPOSAL",me.getModelID().getProposal()); 
      JSONESPAJ.put("GADGET_SPAJ_KEY",me.getModelID().getIDSPAJ()); 
      JSONESPAJ.put("NO_VA",me.getModelID().getVa_number()); 
      JSONESPAJ.put("Dokumen_Pendukung",jsonObjectDP); 

      JSONFINAL.put("ESPAJ", JSONESPAJ); 
      JSONFINAL.put("CLIENT", "ANDROID"); 
      JSONFINAL.put("APP", "ESPAJ"); 

      MultipartEntityBuilder multiPartEntityBuilder= MultipartEntityBuilder.create(); 
    multiPartEntityBuilder.addPart("ESPAJ",JSONFINAL.toString()); 

    httpPost.setEntity(multiPartEntityBuilder.build()); 

    HttpResponse httpResponse = httpclient.execute(httpPost); 


    inputStream = httpResponse.getEntity().getContent(); 
     if(inputStream != null) 
     result = convertInputStreamToString(inputStream); 
    else 
     result = "Did not work!"; 
}catch(OutOfMemoryError e){ 
     Log.e("MEMORY EXCEPTION: ", e.toString()); 
} catch(ConnectTimeoutException e){ 
    Log.e("Timeout Exception: ", e.toString()); 
} catch(SocketTimeoutException ste){  
    Log.e("Timeout Exception: ", ste.toString()); 
} catch (Exception e) { 
// Log.d("InputStream", e.getLocalizedMessage()); 
} 
private static String convertInputStreamToString(InputStream inputStream) throws IOException{ 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
    String line = ""; 
    String result = ""; 
    while((line = bufferedReader.readLine()) != null) 
//  hasil=line; 
     result += line; 

    inputStream.close(); 
    return result; 

} 

有沒有人可以幫助我教和告訴我如何使用MultiPartEntityBuilder發送JSON和圖像?

回答

24

要發送二進制數據,您需要使用addBinaryBody方法MultipartEntityBuilder。附加的示例:

import org.apache.http.entity.ContentType; 
import org.apache.http.entity.mime.MultipartEntityBuilder; 
//Image attaching 
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); 
File file; 
multipartEntity.addBinaryBody("someName", file, ContentType.create("image/jpeg"), file.getName()); 
//Json string attaching 
String json; 
multipartEntity.addPart("someName", new StringBody(json, ContentType.TEXT_PLAIN)); 

然後作出要求像往常一樣:從Apache的

HttpPut put = new HttpPut("url"); 
put.setEntity(multipartEntity.build()); 
HttpResponse response = client.execute(put); 
int statusCode = response.getStatusLine().getStatusCode(); 
+0

因此對於JSON如何發送它? – Menma

+0

@NenMa json只是一個字符串。所以請像平常一樣發送純文本。我已經更新了答案。 – eleven

+0

所以你的意思是我必須首先將我的JSON轉換爲字符串,對吧? – Menma

0
Log.d(LOG_SERVICE_TAG, "Sending Multipart Image with Json data"+");  
    InputStream imageStream; 
    JSONObject objResult; 
    boolean bSucess = true; 
      // Base 64 image string was stored with image object , 
    String imageBase64 = image.getImageString(); 
    // This base64 to byte , One can directly read bytes from file from Disk 
    String imageDataBytes = imageBase64.substring(imageBase64.indexOf(",")+1); 
    HttpClient client = null; 
    HttpPost post = null; 
    HttpResponse response = null; 
    HttpEntity httpEntity = null; 
    String result; 
    imageStream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.DEFAULT)); 
    try{ 
     //Forming Json Object 
     JSONObject jsonImageMetdata = new JSONObject();  
     JSONObject objMultipart = new JSONObject();  
     try { 
      objMultipart.put("param1", "param 1 value"); 
      objMultipart.put("param2", "param 2 value" ); 
      objMultipart.put("param3","param 3 value"); 
      objMultipart.put("param4", "param 4 value");     
      jsonImageMetdata.put("MultipartImageMetadata", objMultipart); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     // converting json data to string 
     String strImageMetadata = jsonImageMetdata.toString(); 
     client = new DefaultHttpClient(); 
     post = new HttpPost("https://abcd"); 
     MultipartEntityBuilder entityBuilder = null; 
     try{ 
      entityBuilder = MultipartEntityBuilder.create(); 
     } 
     catch(Exception a){ 
      Log.d("name",a.getMessage()); 
      throw a;     
     } 
     entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);  

     // adding text 
     entityBuilder.addTextBody("dummyParameter","Dummy text",ContentType.TEXT_PLAIN);    

     // adding Image 
     if(imageStream != null){     
      entityBuilder.addBinaryBody("file", imageStream,ContentType.create("image/jpeg"),"imagename.jpg"); 
     }   

     // sending formed json data in form of text 
     entityBuilder.addTextBody("descriptions", strImageMetadata, ContentType.APPLICATION_JSON) ; 
     HttpEntity entity = entityBuilder.build(); 
     post.setEntity(entity);   
     response = client.execute(post); 
     httpEntity = response.getEntity(); 
     result = EntityUtils.toString(httpEntity); 

下載的HttpCore-4.3.2.jar,httpmime-4.3.3.jar並將它們添加在Android項目的lib文件夾中使用MultipartEntityBuilder

1

有我的解決方案,用於發送圖像和文本字段(與ap疼痛http庫)與POST請求。 Json可以以同樣的方式添加,就像我的田野小組和所有者一樣。

  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