views:

59

answers:

1

Hi,

I am trying to develop a Http client which uploads a file with 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 server side, there is a

doPost(HttpServletRequest request, HttpServletResponse response)

method which parse 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 FileItem's Content-type is null and I have a NullPointerException later. However when I do bin.getContentType() on client side I get "text/xml".

Does someone know when this Content type is lost and how to fix that?

A: 

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

However, STRICT may not work for you because some web servers don't like it.

The default content-type for FileBody is application/octet-stream. You can change it like this,

  FileBody bin = new FileBody(new File(myFile), "text/html");
ZZ Coder
It works perfectly. Thanks a lot!