0

There is the following code:

public static void uploadUserpick(File file) throws URISyntaxException, ClientProtocolException, IOException {  
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(USERPICK_URL);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("upload", new FileBody(file));
    httppost.setEntity(entity);
    HttpResponse response = httpclient.execute(httppost); 
}

There is the following problem - back-end code restricts a MIME type of POST request, therefore I need to set MIME type of my image file (File file). How can I set it?

user2218845
  • 1,081
  • 4
  • 16
  • 21

4 Answers4

2

You should add a "Content-Type" header to the HttpPost based on the format for your image. For example if your file is a GIF image then you should add the header in the following way:

httppost.addHeader(new BasicHeader ("Content-Type", "image/gif"));

Hope it helps.


EDIT

As mentioned in another answer the addHeader method actually has a more straightforward overload than the one I mentioned originally.

httppost.addHeader("Content-Type", "image/gif");
juan.facorro
  • 9,791
  • 2
  • 33
  • 41
0

I found out how to do this here. Just do this:

httppost.addHeader("Content-Type", "application/xml"); 
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
0

You may replace

new FileBody(file)

by

new FileBody(file, "image/jpeg");

See related question and blog post.

Community
  • 1
  • 1
lifus
  • 8,074
  • 1
  • 19
  • 24
0

In case of spring you can do it like this using MediaType class

@RequestMapping(value = { "/xml/private/secure/store.html"}, 
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_XML_VALUE) 
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody 
public StoreDTO returnStoreXML(Model model, 
        @RequestParam(value = "id", required = false) String id,
        @RequestParam(value = "name", required = false) String name) {

}       
Kalher
  • 3,613
  • 2
  • 24
  • 34