ContentType issue with commons-upload and httpcomponent client

I am trying to develop an Http client that uploads a file using httpcomponents:

HttpPost httppost = new HttpPost(myURL);
httppost.setHeader("Content-type",
       "multipart/form-data; boundary=stackoverflow");
httppost.setHeader("Accept", "text/xml");
MultipartEntity reqEntity = new multipartEntity(
       HttpMultipartMode.BROWSER_COMPATIBLE,"stackoverflow",
       Charset.forName("UTF-8"));
FileBody bin = new FileBody(myFile);
reqEntity.addPart("File", bin);
httppost.setEntity(reqEntity);
HttpResponse response = client.execute(httppost);

On the server side there is

doPost(HttpServletRequest request, HttpServletResponse response)

which parses the request:

FileItemFactory factory = new DiskFileItemFactory(204800, new File(
                    uploadDirectory));
ServletFileUpload fileUpload = new ServletFileUpload(factory);
try {
     List<FileItem> items = fileUpload.parseRequest(request);
     Iterator<FileItem> itemIterator = items.iterator();
     while (itemIterator.hasNext()) {
          FileItem item = itemIterator.next();
           ....

It works fine, but the problem is that my ContentItem Content-type is null, and later I have a NullPointerException. However, when I do bin.getContentType () on the client side, I get the text / xml.

Does anyone know when this type of content is lost, and how to fix it?

0
source share
1 answer

You are using the wrong mode. In BROWSER_COMPATIBLE mode, the content type is not sent to the server. To send content_type you need to use STRICT mode.

STRICT , - .

FileBody - application/octet-stream. :

  FileBody bin = new FileBody(new File(myFile), "text/html");
+2

All Articles