HTTP 415 错误 – 不支持的媒体类型(Unsupported media type)

   前段时间在使用@RequestBody注解的时候遇到了一个以前没遇到过的错误,HTTP 415  Unsupported media type? 这个是个什么鬼,@ResponseBody可以正常工作而一使用@RequestBody来进行交互就会报这个错误。一直请求不到Controller,我开始总以为是路径或者json格式不对的问题,上网查资料大多也说的是这个问题。可是我已经写了

data : JSON.stringify(user),  

dataType : 'json',

contentType : 'application/json;charset=UTF-8',

按照网上的办法也一直不管用,百思不得其解。于是继续在网上找资料,

网上分析原因很多,但找了很久都没解决,基本是以下几类:

  • springmvc添加配置、注解;
  • pom.xml添加jackson包引用;
  • Ajax请求时没有设置Content-Type为application/json
  •  发送的请求内容不要转成JSON对象,直接发送JSON字符串即可
各种办法都尝试了一遍,还是没有能解决问题;

<script>
	jQuery(function($){
	var urlStr = "<%=request.getContextPath()%>/user/GetUser";
		var user = {
			"id" : 6,
			"userName" : "小红",
			"password" : "123",
			"age" : 12
		};
		$.ajax({
			url : urlStr,
			type : "POST",
			data : JSON.stringify(user), //转JSON字符串  
			dataType : 'json',
			contentType : 'application/json;charset=UTF-8', //contentType很重要     
			success : function(result) {
				console.log(result);
				//alert(result);
				//data = eval("(" + result + ")");
				//alert(data);
				$("#a").html(result.userName);
			}
		});
	});
</script>
造了一个简单是数据来测试,还是不行。。

package com.cn.hnust.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.hnust.domain.User;
import com.cn.hnust.service.IUserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private IUserService userService;

	@RequestMapping("/showUser")
	public String toIndex(HttpServletRequest request, Model model) {
		// int userId = Integer.parseInt(request.getParameter("id"));
		// User user = this.userService.getUserById(userId);
		// model.addAttribute("user", user);
		return "showUser";
	}

	@RequestMapping(value = "/GetUser", method = RequestMethod.POST)
	public @ResponseBody
	User GetUser(@RequestBody User user) {
		user.setUserName("Wei");
		return user;
	}

}

控制器也很简单,可是就是请求不到Controller方法。于是我继续在网上寻找资料,直到看到一篇博客,才找到了问题的解决办法。


原来是Jackson的依赖问题,spring3.x和spring4.x是不同的:

spring3.x是org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

spring4.x是org.springframework.http.converter.json.MappingJackson2HttpMessageConverter


具体可以查看spring-web的jar确认,哪个存在用哪个!


在配置ViewResolver的时候应该指定响应的版本,于是我将springmvc的配置文件改为:

<bean
		class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
		<property name="order" value="1" />
		<property name="mediaTypes">
			<map>
				<entry key="json" value="application/json" />
				<entry key="xml" value="application/xml" />
				<entry key="htm" value="text/html" />
			</map>
		</property>

		<property name="defaultViews">
			<list>
				<!-- JSON View -->
				<bean
					class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
				</bean>
			</list>
		</property>
		<property name="ignoreAcceptHeader" value="true" />
	</bean>


仅仅将
MappingJacksonJsonView
改为
MappingJackson2JsonView


就解决了之前的415的问题。。。 
发布了21 篇原创文章 · 获赞 7 · 访问量 13万+
展开阅读全文

restTemplate发送post请求时报错

08-28

这个是我发送请求的代码部分逻辑 ``` public String getPortInfo(String hostName){ PortInfo portInfo =new PortInfo(); MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>(); portInfo.setHostName(hostName); portInfo.setIp("8762"); paramMap.add("reqData", JSONObject.toJSONString(portInfo)); String url = "http://ribbon-provider/reqportinfo"; String res = restTemplate.postForObject(url, paramMap, String.class); System.out.println("responsepost json : " + JSONObject.toJSONString(res)); return res; }; ``` 这个是接收post请求的代码部分逻辑 ``` @RequestMapping(value = "/reqportinfo", method = RequestMethod.POST) public String getPortInfo(@RequestBody reqData req){ return helloService.getPortInfo(req) ; } ``` ``` public class reqData { private String hostName; private String ip; //省略get set } ``` 提示的错误 org.springframework.web.client.HttpClientErrorException$UnsupportedMediaType: 415 null at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:95) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:122) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:102) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:778) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:736) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:414) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] at com.fangsir.ribbonnconsumer.Service.HelloService.getPortInfo(HelloService.java:26) ~[classes/:na] at com.fangsir.ribbonnconsumer.controller.HelloController.getPortInfo(HelloController.java:24) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.22.jar:9.0.22] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.22.jar:9.0.22] 问答

前台报错 415 (Unsupported Media Type)

08-07

<script> //异步上传图片 function doploy(){ //定义参数 var options={ url:"rest/process/deploy/", dataType:"text", type:"post", success:function(data){ alert(data); }, error:function(){ alert("upload error"); } }; //使用jquery.form异步上传图片 $("#deployProcess").ajaxSubmit(options); } </script> </head> <body> <div id="d1"> <form action="" method="post" enctype="multipart/form-data" id="deployProcess"> <label> 请选择发布的流程:<input type="file" name="processDef" /> </label> <label> <input type="button" value="提交" onclick="doploy()" /> </label> </form> </div> </body> @POST @Path("/deploy/") @Produces(MediaType.APPLICATION_JSON) @LogAnnotation(operationName = "发布流程") public String deployProcess(@RequestParam(required=false) MultipartFile processDef) { ZipInputStream zis = null; HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); try { request.setCharacterEncoding("UTF-8"); String deployFile = request.getParameter("processDef"); if (deployFile != null && !deployFile.isEmpty()) { ProcessEngine processEngine = Configuration.getProcessEngine(); RepositoryService repositoryService = processEngine .getRepositoryService(); zis = new ZipInputStream(processDef.getInputStream()); repositoryService.createDeployment() .addResourcesFromZipInputStream(zis).deploy(); zis.close(); } else { return GlobalConstant.FAILURE; } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); return GlobalConstant.FAILURE; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return GlobalConstant.FAILURE; } finally { try { if(zis != null){ zis.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return GlobalConstant.SUCCESS; } 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览