Sending images using Http Post

前端 未结 5 1154
轮回少年
轮回少年 2020-11-22 05:52

I want to send an image from the android client to the Django server using Http Post. The image is chosen from the gallery. At present, I am using list value name Pairs to s

5条回答
  •  心在旅途
    2020-11-22 06:15

    Version 4.3.5 Updated Code

    • httpclient-4.3.5.jar
    • httpcore-4.3.2.jar
    • httpmime-4.3.5.jar

    Since MultipartEntity has been deprecated. Please see the code below.

    String responseBody = "failure";
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    
    String url = WWPApi.URL_USERS;
    Map map = new HashMap();
    map.put("user_id", String.valueOf(userId));
    map.put("action", "update");
    url = addQueryParams(map, url);
    
    HttpPost post = new HttpPost(url);
    post.addHeader("Accept", "application/json");
    
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(MIME.UTF8_CHARSET);
    
    if (career != null)
        builder.addTextBody("career", career, ContentType.create("text/plain", MIME.UTF8_CHARSET));
    if (gender != null)
        builder.addTextBody("gender", gender, ContentType.create("text/plain", MIME.UTF8_CHARSET));
    if (username != null)
        builder.addTextBody("username", username, ContentType.create("text/plain", MIME.UTF8_CHARSET));
    if (email != null)
        builder.addTextBody("email", email, ContentType.create("text/plain", MIME.UTF8_CHARSET));
    if (password != null)
        builder.addTextBody("password", password, ContentType.create("text/plain", MIME.UTF8_CHARSET));
    if (country != null)
        builder.addTextBody("country", country, ContentType.create("text/plain", MIME.UTF8_CHARSET));
    if (file != null)
        builder.addBinaryBody("Filedata", file, ContentType.MULTIPART_FORM_DATA, file.getName());
    
    post.setEntity(builder.build());
    
    try {
        responseBody = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");
    //  System.out.println("Response from Server ==> " + responseBody);
    
        JSONObject object = new JSONObject(responseBody);
        Boolean success = object.optBoolean("success");
        String message = object.optString("error");
    
        if (!success) {
            responseBody = message;
        } else {
            responseBody = "success";
        }
    
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        client.getConnectionManager().shutdown();
    }
    

提交回复
热议问题