quocvuongdn icon

#java: http client post image file multipart/data

quocvuongdn | PRO | 08/28/14 10:27:26 AM UTC | 0 ⭐ | 504 👁️ | Never ⏰ | []
Java |

1.41 KB

|

None

|

0 👍

/

0 👎

public void send() throws IOException{
        //data
        JSONObject jObj = new JSONObject();
        jObj.put("full_name","Vương");
        jObj.put("birthday", "2014-08-12");
        jObj.put("id", "228822");
        
        HttpClient httpClient = new DefaultHttpClient();
        
        File file=new File("C:/image.jpg");
        HttpPost httpPost = new HttpPost("http://");
        httpPost.setHeader("enctype", "multipart/form-data");
        
        StringBody comment = new StringBody(jObj.toString(), ContentType.TEXT_PLAIN); //chưa encrypt
        StringBody command = new StringBody("U_UPDATE_USER_INFO_SDK", ContentType.TEXT_PLAIN);
        
        MultipartEntity  multipart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipart.addPart("avatar", new FileBody(file));
        multipart.addPart("data", comment);  
        multipart.addPart("command", command);
        
        httpPost.setEntity(multipart);
        HttpResponse response = httpClient.execute(httpPost);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent(),"UTF-8"
        ));
        String sResponse;
        StringBuilder s = new StringBuilder();
        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse);
        }
        
        System.out.println("Response for POST:"+s);
    }

Comments