Android- POST multipart form data

后端 未结 3 1672
南方客
南方客 2020-12-02 17:47

I would like to send multipart form with video and data such as Email and name. The following is my code and it does not work ,there is no response from the server



        
3条回答
  •  时光取名叫无心
    2020-12-02 18:16

    There is my working solution (I hope simpler) for sending image with post, using apache http libraries (very important here is boundary add It won't work without it in my connection). I hope it could help in such situation:

                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
    

提交回复
热议问题