Multipart/form-data construction with android

纵饮孤独 提交于 2019-11-29 07:38:59

So after searching high and low for an answer, and almost giving up, this link finally helped

here is the final working code:

 public HttpResponse invokeXAUTHPOSTService(String url, String token, File file) {

    client = new DefaultHttpClient();

    HttpPost request = new HttpPost(url);

    HttpResponse response = null;

    DRPContentForUpload content = new DRPContentForUpload(file);
    String jsonObject = DRPJSONConverter.toJson(content);
    String BOUNDARY= "--eriksboundry--";

    request.setHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
    request.addHeader("X-AUTHORIZATION",token);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,BOUNDARY,Charset.defaultCharset());
    try {


        entity.addPart("file01", new StringBody(jsonObject));

        entity.addPart("file01", new FileBody(file));

        request.addHeader("Accept-Encoding", "gzip, deflate");

    } catch (UnsupportedEncodingException e) {
        Log.v("encoding exception","E::: "+e);
        e.printStackTrace();
    }
    request.setHeader("Accept", "application/json");
    request.setHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
    request.setEntity(entity);

    try {




        response = client.execute(request);



    } catch (ClientProtocolException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }


    return response;

}

Is the problem that the mime-type for your image isn't being set properly? Try to use the alternative constructor for FileBody:

FormBodyPart part2 = new FormBodyPart("file01", new FileBody(file, "image/jpeg"));

Giving both parts of the multi-part request the same name is a bit suspicious, but it doesn't seem to be causing you problems here.

If you want to see what your body looks like before sending, try using EntityUtils.toString(Entity) on the multi-part entity after adding all of the elements. The image is simply binary so won't print very well, but the headers should be readable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!