REST-клиент с использованием Spring Boot - PullRequest
0 голосов
/ 16 мая 2018

Я пишу клиент для веб-сервиса REST, используя пример на весеннем веб-сайте. https://spring.io/guides/gs/consuming-rest/

Мое ограничение заключается в том, что я должен использовать JDK1.6 для этой разработки.

Клиентское приложение (заменяющее Lambda анонимным вызовом метода) выдает ошибку, и я не могу найти исправление. Любая помощь будет высоко ценится.

Сообщение об ошибке:

The method setSupportedMediaTypes(List<MediaType>) in the type AbstractHttpMessageConverter<Object> is not applicable for the arguments (List<Object>)

Application.java

package main.java.hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;;
//import com.fasterxml.jackson.core.*;

@SpringBootApplication
public class Application {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String args[]) {
        SpringApplication.run(Application.class);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Bean
    public CommandLineRunner run(final RestTemplate restTemplate) throws Exception {
        return new CommandLineRunner() {

            @Override
            public void run(String... args) throws Exception {

                List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();        

                //Add the Jackson Message converter
                MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

                // Note: here we are making this converter to process any kind of response, 
                // not only application/*json, which is the default behaviour
                converter.setSupportedMediaTypes(Arrays.asList({MediaType.ALL}));         
                messageConverters.add(converter); 

                Quote quote = restTemplate.getForObject(
                        "http://gturnquist-quoters.cfapps.io/api/random", Quote.class);
                log.info(quote.toString());
            }
        };
    }
}

Quote.java

package main.java.hello;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {

    private String type;
    private Value value;

    public Quote() {
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Value getValue() {
        return value;
    }

    public void setValue(Value value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Quote{" +
                "type='" + type + '\'' +
                ", value=" + value +
                '}';
    }
}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>WebServiceClient</groupId>
  <artifactId>WebServiceClient</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.17.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.17.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot</artifactId>
        <version>1.5.13.RELEASE</version>
    </dependency>    

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
        <version>1.5.13.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.25</version>
    </dependency>



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

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.5</version>
    </dependency>  

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

  </dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Спасибо!

1 Ответ

0 голосов
/ 16 мая 2018

Определенно что-то не так со следующей строкой в ​​методе run():

converter.setSupportedMediaTypes(Arrays.asList({MediaType.ALL})); 

Arrays.asList имеет следующую подпись:

public static <T> List<T> asList(T... a) { ... }

Так что вы можете использовать это так (если вам нужно передать несколько аргументов):

converter.setSupportedMediaTypes(Arrays.asList(new MediaType[]{MediaType.ALL}));

или

converter.setSupportedMediaTypes(Arrays.asList(MediaType.ALL));

Пожалуйста, попробуйте это и проверьте, если это имеет какое-либо значение.

UPDATE

Для JDK 1.6 вам может понадобиться понизить рейтинг Джексона до 1.9.13. Я нашел кое-что:

<!-- core on 1 version -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<!-- databind in version 1 -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

Но я ничего не нашел для jackson-annotations, нет аналогичного модуля для версии 1. Может быть, вы могли бы попробовать без него и посмотреть, работает ли он.

Не уверен, как это будет работать с новой версией Spring.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...