How to get Entity on a servlet using MultipartEntity?

If I upload a file to my servlet like this:

HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.tumblr.com/api/write"); try { MultipartEntity entity = new MultipartEntity(); entity.addPart("type", new StringBody("photo")); entity.addPart("data", new FileBody(image)); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); } catch (ClientProtocolException e) {} catch (IOException e) {} 

How can I get the content on a servlet?

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { request.??? } 
  • I use the Google app server as my servlet API
+4
source share
1 answer

If the version of your servlet container or server or engine is <3.0 (for example, 2.5 or earlier), you can use the third-party library Apache Commons FileUpload . Although the file was intended to be used for downloaded files, it also works effectively with downloaded data from POST Methods, as described here .

The servlet API, starting with version 3.0, offers some calls in another to deal with published data, and has been sent to a POST-Request. the only requirement is that the encoding of the MIME type of your content is a " multipart / form-data " object.

then you can get every "part" of your content using:

  • getPart (String partName) : where "partName" is the name of the part of your multi-contact object.

     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String partName = "type"; // or "data" Part part = request.getPart(partName); // read your StringBody type BufferedReader reader = new BufferedReader( new InputStreamReader(part.getInputStream())); String line =""; while((line=reader.readLine())!=null) { // do Something with a line System.out.println(line); } // or with a binary Data partName="data"; part = request.getPart(partName); // read your FileBody data InputStream is = part.getInputStream(); // do Something with you byte data is.read(); // is.read(b); // .. } 
  • getParts () :

it achieves the same results as getPart (partName), while the data here is the aggregate of the entire portion of the data sent. to get every element of a part of this collection, just use thread iteration over the collection:

 Iterator<Part> iterator = request.getParts().iterator(); Part parts = null; while (iterator.hasNext()) { parts = (Part) iterator.next(); //rest of the code block removed } } 

Since getPart () / getParts () only works with Servlet 3.0, you will definitely use the Servlet support container and / or update the current servlet container. some server or servlet container that supports 3.0:

+4
source

Source: https://habr.com/ru/post/1412952/


All Articles