具有多部分请求的android rest模板
案例1:发送实体类作为请求[工作] 案例2:按请求发送图像(多部分)[工作] 案例3:发送实体+图像[不工作] 案例1:具有多部分请求的android rest模板,android,spring,rest,spring-mvc,resttemplate,Android,Spring,Rest,Spring Mvc,Resttemplate,案例1:发送实体类作为请求[工作] 案例2:按请求发送图像(多部分)[工作] 案例3:发送实体+图像[不工作] 案例1: @RequestMapping(value = "/add", method = RequestMethod.POST) public @ResponseBody String add(@RequestBody SampleEntity sampleEntity) { return "From Server: " + sampleEntity.getId(); }
@RequestMapping(value = "/add", method = RequestMethod.POST)
public @ResponseBody String add(@RequestBody SampleEntity sampleEntity) {
return "From Server: " + sampleEntity.getId();
}
@RequestMapping(value = "/imagepart", method = RequestMethod.POST)
public @ResponseBody String imagePart(@RequestPart("image") MultipartFile file) {
return "From Server(ImagePart): " + file.getOriginalFilename();
}
@RequestMapping(value = "/addimagepart", method = RequestMethod.POST)
public @ResponseBody String addPart(
@RequestPart("sampleEntity") SampleEntity sampleEntity,
@RequestPart("image") MultipartFile file) {
return "From Server(Part) : " + sampleEntity.getId() + " "
+ file.getOriginalFilename();
}
测试用例1
输出:来自服务器:123
案例2:
@RequestMapping(value = "/add", method = RequestMethod.POST)
public @ResponseBody String add(@RequestBody SampleEntity sampleEntity) {
return "From Server: " + sampleEntity.getId();
}
@RequestMapping(value = "/imagepart", method = RequestMethod.POST)
public @ResponseBody String imagePart(@RequestPart("image") MultipartFile file) {
return "From Server(ImagePart): " + file.getOriginalFilename();
}
@RequestMapping(value = "/addimagepart", method = RequestMethod.POST)
public @ResponseBody String addPart(
@RequestPart("sampleEntity") SampleEntity sampleEntity,
@RequestPart("image") MultipartFile file) {
return "From Server(Part) : " + sampleEntity.getId() + " "
+ file.getOriginalFilename();
}
测试用例2
测试用例3
错误:此案例失败(图像不工作的实体类)
如何从android rest模板向spring mvc服务器发出请求实体+多部分请求在案例3中,
FormHttpMessageConverter
用于转换多值映射
对象以发送HTTP请求。不幸的是,默认FormHttpMessageConverter不支持将实体转换为JSON。因此,您必须手动将一些JSON转换器(例如,MappingJackson2HttpMessageConverter
)添加到FormHttpMessageConverter
。请尝试使用以下代码:
FormHttpMessageConverter converter = new FormHttpMessageConverter();
converter.addPartConverter(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(0, converter);
从请求对象获取多部分数据,而不是多部分文件注释
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Set set = multipartRequest.getFileMap().entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.println("key :" + me.getKey() + "-"
+ me.getKey().getClass() + "|||||" + "value :"
+ me.getValue() + "-" + me.getValue().getClass());
switch ((String) me.getKey()) {
case "staffPhoto": {
System.out.println("case staffImage "
+ ((MultipartFile) me.getValue())
.getOriginalFilename());
// processImage
break;
}
}
你解决这个问题了吗?我和你面临着同样的问题。。请分享你的发现