如何将MIME类型添加到POST请求Java?

时间:2013-06-19 20:05:22

标签: java

有以下代码:

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); 
}

存在以下问题 - 后端代码限制POST请求的MIME类型,因此我需要设置我的图像文件的MIME类型(文件文件)。我怎么设置它?

4 个答案:

答案 0 :(得分:2)

您应该根据图片的格式向"Content-Type"添加HttpPost标头。例如,如果您的file GIF 图片,那么您应该按以下方式添加标题:

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

希望它有所帮助。


修改

正如另一个答案中所提到的,addHeader方法实际上比我原先提到的方法更容易过载。

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

答案 1 :(得分:0)

I found out how to do this here.就这样做:

httppost.addHeader("Content-Type", "application/xml"); 

答案 2 :(得分:0)

您可以替换

new FileBody(file)

通过

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

See related questionblog post

答案 3 :(得分:0)

如果是春天你可以使用MediaType

这样做
@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) {

}