Android:使用 MultiPartEntityBuilder 上传图像和 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24239923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:55:32  来源:igfitidea点击:

Android : upload Image and JSON using MultiPartEntityBuilder

androidjsonhttp-postmultipartentity

提问by Menma

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 base64and send my another data and image that I've convert before with JSON, but I face Problem OutOfMemoryhere, 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 :

我尝试将数据上传到服务器,我的数据包含多个图像和大JSON,在它之前,我尝试使用将图像转换为字符串base64发送并发送我之前使用的另一个数据和图像JSON,但我OutOfMemory在这里遇到问题,所以我读了一个解决方案,说我必须尝试使用MultipartEntityBuilder. 我仍然很困惑,不明白该怎么做MultiPartEntityBuilder,有没有人可以帮助我做到这一点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;

}   

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

有没有人可以帮助我教我如何使用 MultiPartEntityBuilder 发送 JSON 和图像?

回答by eleven

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

要发送的二进制数据,你需要使用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));

Then make request as usual:

然后像往常一样发出请求:

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

回答by Krystian

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.

有我的解决方案,用于通过 POST 请求发送图像和文本字段(使用 apache http 库)。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

回答by user2502741

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

Download httpcore-4.3.2.jar , httpmime-4.3.3.jar from Apache and add them in lib folder of Android project for using MultipartEntityBuilder

从 Apache 下载 httpcore-4.3.2.jar , httpmime-4.3.3.jar 并将它们添加到 Android 项目的 lib 文件夹中以使用 MultipartEntityBuilder