简体   繁体   English

415 不支持的媒体类型(org.springframework.web.client.HttpClientErrorException)

[英]415 Unsupported Media Type (org.springframework.web.client.HttpClientErrorException)

I am new to WebServices.我是 Web 服务的新手。 I am working on an application where I am using AnhularJs1.x at client side which sends data to Spring Rest Controller.我正在开发一个应用程序,我在客户端使用 AnhularJs1.x 将数据发送到 Spring Rest Controller。

The architecture of the application is micro-services based.应用程序的架构是基于微服务的。 I am able to receive the data from angular to Front end Rest Controller which are in the same war.我能够从 angular 接收数据到同一场战争中的前端休息控制器。

From this controller I am calling a service which internally calls another micro-service which interacts with database.我从这个控制器调用一个服务,该服务在内部调用另一个与数据库交互的微服务。

When I am sending the data received in my front end controller to another micro-service I get 415 Unsupported Media Type (org.springframework.web.client.HttpClientErrorException)当我将前端控制器中接收到的数据发送到另一个微服务时,我得到415 Unsupported Media Type (org.springframework.web.client.HttpClientErrorException)

Below is my front end controller which is in the same war as angularJS下面是我的前端控制器,它与 angularJS 处于同一场战争中

@RequestMapping(value = "/servicearticles",  method = RequestMethod.POST,        produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ServiceArticle> saveData(@RequestBody      List<ServiceArticle> serviceArticleList){
    System.out.println("In savedata");
    System.out.println(serviceArticleList.toString());


    try {
        if(null != serviceArticleList && serviceArticleList.size() >0){
            serviceArticleAdminService.insertData(serviceArticleList);
        }else{
            logger.error("File is empty. No data to save");
        }

I am able to get data in this contoller : [ServiceArticle [articleId=17070, productCode=1000, productName=Business Parcel zone , zone=1], ServiceArticle [articleId=17071, productCode=1001, productName=Business Parcel zone , zone=4], ServiceArticle [articleId=17070, productCode=1012, productName=Business Parcel zone , zone=5], ServiceArticle [articleId=17070, productCode=1000, productName=Business Parcel zone , zone=1], ServiceArticle [articleId=17070, productCode=1000, productName=Business Parcel zone , zone=2]]我能够在这个控制器中获取数据:[ServiceArticle [articleId=17070, productCode=1000, productName=Business Parcel zone , zone=1], ServiceArticle [articleId=17071, productCode=1001, productName=Business Parcel zone , zone= 4], ServiceArticle [articleId=17070, productCode=1012, productName=Business Parcel zone , zone=5], ServiceArticle [articleId=17070, productCode=1000, productName=Business Parcel zone , zone=1], ServiceArticle [articleId=17070 , productCode=1000, productName=Business Parcel zone , zone=2]]

When I call the different microservice from my serviceImpl class I get the unsupported media type error当我从 serviceImpl 类调用不同的微服务时,我收到了不受支持的媒体类型错误

Code for serviceImpl class serviceImpl 类的代码

private final String URI = "http://localhost:8082/admin/import/servicearticles";

@Override
public void insertData(List<ServiceArticle> serviceArticles) {
    logger.error("Inside insertData() in service");

    RestTemplate restTemplate = new RestTemplate();

    try {
            restTemplate.postForObject(URI, serviceArticles, ServiceArticle.class);
    } catch (ResourceAccessException e) {
        logger.error("ServiceArticleAdmin Service Unavailable.");

Below is the code for the controller in different micro-servie which maps to this call下面是映射到这个调用的不同微服务中控制器的代码

@RequestMapping(value = "/import/servicearticles", method =    RequestMethod.POST, consumes= MediaType.APPLICATION_JSON_VALUE , produces = MediaType.APPLICATION_JSON_VALUE)
 public ResponseEntity<ServiceArticle> addAll(@RequestBody List<ServiceArticle> serviceArticles) {

    List<ServiceArticle> serviceArticlesAdded = serviceArticleAdminService.addAll(serviceArticles);

    return new ResponseEntity(serviceArticlesAdded, HttpStatus.OK);
}

I have added the below dependencies in my pom.xml我在 pom.xml 中添加了以下依赖项

   <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.6</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.8.6</version>
    </dependency>

I have the following bean definition in my servlet-context.xml我的 servlet-context.xml 中有以下 bean 定义

<bean
    class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter" />
        </list>
    </property>
</bean>

<!-- To convert JSON to Object and vice versa -->
<bean id="jsonMessageConverter"
    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>

Please help me figure out where am I making a mistake.请帮我弄清楚我在哪里犯了错误。 Is there any way I can set response type as application/json when I am invoking restTemplate.postForObject method当我调用 restTemplate.postForObject 方法时,有什么方法可以将响应类型设置为 application/json

I verified using a REST client plugin it works there but not through my Java code.我使用 REST 客户端插件验证它在那里工作,但不是通过我的 Java 代码。 Please help.请帮忙。

It seems that Content-Type: application/json header is missing.似乎缺少Content-Type: application/json标头。 Your method also returns a list of articles, not a single article, so the third argument in postForObject method is not correct.您的方法还返回文章列表,而不是一篇文章,因此postForObject方法中的第三个参数不正确。

The following code should do the job:以下代码应该可以完成这项工作:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<List<ServiceArticle>> request = new HttpEntity<>(serviceArticles, headers);

ResponseEntity<List<ServiceArticle>> response = 
    restTemplate.exchange(URI, HttpMethod.POST, request,
        new ParameterizedTypeReference<List<ServiceArticle>>() { });
@RestController
@RequestMapping("/db")
public class EmployeeDataServerResource {

    @Autowired
    EmployeeInterface ei;

    @PostMapping("/add")
    public EmployeeTable addEmployee(@Valid @RequestBody EmployeeTable      employeeTable) {

         ei.save(employeeTable);
         return employeeTable;
    }
}

This is my method of restController这是我的restController方法

public String onSave() {    
    try {
    EmployeeTable et = new EmployeeTable();
    et.setFirstName(firstName.getValue());
    et.setLastName(lastName.getValue());
    et.setEmail(email.getValue());
    et.setBirthdate(birthDate.getValue());
    et.setNumber(number.getValue());
    et.setPassword(pswd.getValue());
    et.setGender(rgroup.getValue());
    et.setCountry(select.getValue());
    et.setHobbiesLst(hobbies);

    String uri = "http://localhost:8090/db/add"; 
              
    HttpHeaders headers=new HttpHeaders();
    headers.set("Content-Type", "application/json");
    HttpEntity requestEntity=new HttpEntity(et, headers);

    ResponseEntity<EmployeeTable> addedRes = restTemplate.exchange(uri, HttpMethod.POST,requestEntity,EmployeeTable.class);
    return ""+addedRes.getStatusCodeValue();
      
    }catch (Exception e) {
        System.out.println(""+e.toString());
        return e.toString();
    }   
}

This is for add new employee in database using restController.这是用于使用 restController 在数据库中添加新员工。 It worked for me... Thanks它对我有用...谢谢

This code may solve both of your problems:此代码可以解决您的两个问题:

@RequestMapping(value = "/postnotewithclient",method = RequestMethod.POST)
public String postNote(@RequestBody  Note notes)
{
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<Note> entity = new  HttpEntity<Note>(notes,headers);
    return restTemplate.exchange("http://localhost:8080/api/notes", HttpMethod.POST, entity, String.class).getBody();

}

In my case everything was ok for post request but still unsupported exception was reported.在我的情况下,发布请求一切正常,但仍然报告了不受支持的异常。 After some tweaks to code, the real problem came into light and that was because of Custom Deserializer that I had for one of my fields在对代码进行了一些调整后,真正的问题浮出水面,那是因为我在我的一个领域中使用了自定义反序列化器

Debugging tip: To make sure that your rest API is functioning fine.调试提示:确保您的 rest API 运行良好。 First try to receive the request as string and then try to convert that string using object mapper to required object.首先尝试以字符串的形式接收请求,然后尝试使用对象映射器将该字符串转换为所需的对象。

Above tip in any way should not be used for production ready code .以上提示无论如何都不应用于生产就绪代码。 Hope this helps someone希望这有助于某人

Cheers!干杯!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 org.springframework.web.client.HttpClientErrorException:415 null(Spring Resttemplate) - org.springframework.web.client.HttpClientErrorException: 415 null(Spring Resttemplate) org.springframework.web.client.HttpClientErrorException:400错误的请求 - org.springframework.web.client.HttpClientErrorException: 400 Bad Request org.springframework.web.client.HttpClientErrorException$BadRequest: 400 错误请求 - org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request org.springframework.web.client.HttpClientErrorException:401空 - org.springframework.web.client.HttpClientErrorException: 401 null org.springframework.web.client.HttpClientErrorException: 400 错误的 PUT 请求 - org.springframework.web.client.HttpClientErrorException: 400 Bad Request for PUT org.springframework.web.client.HttpClientErrorException$Unauthorized&#39; 异常 - org.springframework.web.client.HttpClientErrorException$Unauthorized' exception org.springframework.web.client.HttpClientErrorException:RestTemplate 中的 400 错误请求 - org.springframework.web.client.HttpClientErrorException: 400 Bad Request in RestTemplate org.springframework.web.client.HttpClientErrorException 400 RestTemplate.postForEntity - org.springframework.web.client.HttpClientErrorException 400 RestTemplate.postForEntity org.springframework.web.client.HttpClientErrorException:400空 - org.springframework.web.client.HttpClientErrorException: 400 null RestTemplate.postForObject - 错误:org.springframework.web.client.HttpClientErrorException:400错误请求 - RestTemplate.postForObject - Error: org.springframework.web.client.HttpClientErrorException: 400 Bad Request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM