quocvuongdn

#java: http client post image file multipart/data

Aug 28th, 2014
435
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. public void send() throws IOException{
  2.         //data
  3.         JSONObject jObj = new JSONObject();
  4.         jObj.put("full_name","Vương");
  5.         jObj.put("birthday", "2014-08-12");
  6.         jObj.put("id", "228822");
  7.        
  8.         HttpClient httpClient = new DefaultHttpClient();
  9.        
  10.         File file=new File("C:/image.jpg");
  11.         HttpPost httpPost = new HttpPost("http://");
  12.         httpPost.setHeader("enctype", "multipart/form-data");
  13.        
  14.         StringBody comment = new StringBody(jObj.toString(), ContentType.TEXT_PLAIN); //chưa encrypt
  15.         StringBody command = new StringBody("U_UPDATE_USER_INFO_SDK", ContentType.TEXT_PLAIN);
  16.        
  17.         MultipartEntity  multipart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
  18.         multipart.addPart("avatar", new FileBody(file));
  19.         multipart.addPart("data", comment);  
  20.         multipart.addPart("command", command);
  21.        
  22.         httpPost.setEntity(multipart);
  23.         HttpResponse response = httpClient.execute(httpPost);
  24.         BufferedReader reader = new BufferedReader(new InputStreamReader(
  25.                 response.getEntity().getContent(),"UTF-8"
  26.         ));
  27.         String sResponse;
  28.         StringBuilder s = new StringBuilder();
  29.         while ((sResponse = reader.readLine()) != null) {
  30.             s = s.append(sResponse);
  31.         }
  32.        
  33.         System.out.println("Response for POST:"+s);
  34.     }
Advertisement
Add Comment
Please, Sign In to add comment