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

时间:2017-02-12 11:01:39

标签: java spring rest spring-mvc

我是WebServices的新手。我正在开发一个应用程序,我在客户端使用AnhularJs1.x将数据发送到Spring Rest Controller。

该应用程序的架构是基于微服务的。我能够从角度到前端静止控制器接收数据,这些数据处于相同的战争中。

我从这个控制器调用一个内部调用另一个与数据库交互的微服务的服务。

当我将前端控制器收到的数据发送到另一个微服务时,我得到 415不支持的媒体类型(org.springframework.web.client.HttpClientErrorException)

下面是我的前端控制器,与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");
        }

我可以在此控制器中获取数据: [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]]

当我从serviceImpl类调用不同的微服务时,我得到了不支持的媒体类型错误

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.");

以下是映射到此调用的不同微服务中控制器的代码

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

我在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>

我的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>

请帮我弄清楚我在哪里弄错了。 有什么办法可以在我调用时将响应类型设置为application / json restTemplate.postForObject方法

我使用REST客户端插件验证了它在那里工作但不是通过我的Java代码。请帮忙。

4 个答案:

答案 0 :(得分:5)

似乎&#34;内容类型:application / json&#34;标头丢失了。 您的方法也适用于文章列表,因此postForObject方法中的第三个参数不正确。

以下代码应该完成这项工作:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<List<ServiceArticle>> request = new HttpEntity<>(serviceArticles, headers);
restTemplate.exchange(URI, HttpMethod.POST, request, new ParameterizedTypeReference<List<ServiceArticle>>() { });

答案 1 :(得分:1)

@RestController
@RequestMapping("/db")
public class EmployeeDataServerResource {

    @Autowired
    EmployeeInterface ei;

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

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

这是我的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();
    }   
}

这用于使用restController在数据库中添加新员工。 它对我有用... 谢谢

答案 2 :(得分:0)

此代码可以解决您的两个问题:

  document.addEventListener('DOMContentLoaded', function() {
    var initialLocaleCode = 'fr';
    var localeSelectorEl = document.getElementById('locale-selector');
    var calendarEl = document.getElementById('calendar');

   var calendar = new FullCalendar.Calendar(calendarEl, {
      plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'list' ],
      header: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay,list'
      },
      locale: initialLocaleCode,
      buttonIcons: false,
      weekNumbers: true,
      navLinks: true,
      editable: true,
      eventLimit: true, // allow "more" link when too many events
      events: "events.php",

答案 3 :(得分:0)

就我而言,发布请求一切正常,但仍然报告了不受支持的异常。经过一些代码调整后,真正的问题暴露出来了,这是因为我在其中一个字段中拥有的自定义 反序列化器

调试提示: 为了确保您的其余API正常运行。首先尝试以字符串形式接收请求,然后尝试使用对象映射器将该字符串转换为所需的对象。

以上技巧均不应用于生产就绪代码。希望这对某人有帮助

干杯!