Post multipart request with Android SDK

前端 未结 12 1993
余生分开走
余生分开走 2020-11-22 04:38

I\'m trying to do something I thought would be relatively simple: Upload an image to a server with the Android SDK. I\'m found a lot of example code:

http://groups.g

12条回答
  •  别那么骄傲
    2020-11-22 05:21

    As MultiPartEntity is deprecated. So here is the new way to do it! And you only need httpcore.jar(latest) and httpmime.jar(latest) download them from Apache site.

    try
    {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(URL);
    
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    
        entityBuilder.addTextBody(USER_ID, userId);
        entityBuilder.addTextBody(NAME, name);
        entityBuilder.addTextBody(TYPE, type);
        entityBuilder.addTextBody(COMMENT, comment);
        entityBuilder.addTextBody(LATITUDE, String.valueOf(User.Latitude));
        entityBuilder.addTextBody(LONGITUDE, String.valueOf(User.Longitude));
    
        if(file != null)
        {
            entityBuilder.addBinaryBody(IMAGE, file);
        }
    
        HttpEntity entity = entityBuilder.build();
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        HttpEntity httpEntity = response.getEntity();
        result = EntityUtils.toString(httpEntity);
        Log.v("result", result);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    

提交回复
热议问题