Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : upload Image and JSON using MultiPartEntityBuilder

I try to upload data to server, my data containing multiple images and large JSON, before it, I Try to send with convert image to string using base64 and send my another data and image that I've convert before with JSON, but I face Problem OutOfMemory here, so I read one of solutions that said I must to try using MultipartEntityBuilder. I still confusing and not understand how to do it with MultiPartEntityBuilder, Is there anyone can help me the way to do it with MultiPartEntityBuilder? this is my code :

    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;

}   

is there anyone can help me to teach and tell me how to send JSON and Image using MultiPartEntityBuilder?

like image 343
Menma Avatar asked Jun 16 '14 08:06

Menma


2 Answers

To send binary data you need to use addBinaryBody method of MultipartEntityBuilder. Sample of attaching:

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

Then make request as usual:

HttpPut put = new HttpPut("url");
put.setEntity(multipartEntity.build());
HttpResponse response = client.execute(put);
int statusCode = response.getStatusLine().getStatusCode();
like image 182
eleven Avatar answered Nov 03 '22 04:11

eleven


There is my solution, for sending images and text fields (with apache http libraries) with POST request. Json could be added in the same way, as my fields group and owner.

            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
like image 1
Krystian Avatar answered Nov 03 '22 02:11

Krystian