Spring MVC 如何将RestTemplate与应用程序/八位字节流响应类型一起使用

p5fdfcr1  于 2023-03-08  发布在  Spring
关注(0)|答案(3)|浏览(187)

我使用ISBNdB来获取书籍的信息,响应类型是application/octet-stream,json响应示例如下所示

{
"index_searched" : "isbn",
"data" : [
  {
     "publisher_id" : "john_wiley_sons_inc",
     "publisher_name" : "John Wiley & Sons, Inc",
     "title_latin" : "Java programming interviews exposed",
     "language" : "eng",
     "summary" : "",
     "physical_description_text" : "1 online resource (xvi, 368 pages) :",
     "author_data" : [
        {
           "name" : "Markham, Noel",
           "id" : "markham_noel"
        },
        {
           "id" : "greg_milette",
           "name" : "Greg Milette"
        }
     ],
     "title_long" : "Java programming interviews exposed",
     "urls_text" : "",
     "publisher_text" : "New York; John Wiley & Sons, Inc",
     "book_id" : "java_programming_interviews_exposed",
     "awards_text" : "; ",
     "subject_ids" : [],
     "isbn13" : "9781118722862",
     "lcc_number" : "",
     "title" : "Java programming interviews exposed",
     "isbn10" : "1118722868",
     "dewey_decimal" : "005.13/3",
     "edition_info" : "; ",
     "notes" : "\"Wrox programmer to programmer\"--Cover.; Acceso restringido a usuarios UCM = For UCM patrons only.",
     "marc_enc_level" : "",
     "dewey_normal" : "5.133"
  }
  ]
  }

我使用Jackson来转换这个响应。我的Pojo如下所示

@JsonIgnoreProperties(ignoreUnknown = true)

public class value {
    private  String index_searched;
    // Another pojo in different file with ignore properties
    private data[] dat;

    public value(){

    }
    public data[] getDat() {
        return dat;
    }

    public void setDat(data[] dat) {
        this.dat = dat;
    }
    public String getIndex_searched() {
        return index_searched;
    }
    public void setIndex_searched(String index_searched) {
        this.index_searched = index_searched;
    } 
   }

当我试着跟踪

value book = restTemplate.getForObject(FINAL_URL, value.class);

我得到这个异常

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.rocketrenga.mylibrary.domain.value] and content type [application/octet-stream]

但是我可以将响应Map到String

String book = restTemplate.getForObject(FINAL_URL, String.class);
ObjectMapper mapper = new ObjectMapper();
value val = mapper.readValue(book, value.class);
System.out.println(val.getIndex_searched());

如何将响应直接Map为POJO而不是String,并将其转换回POJO

avwztpqn

avwztpqn1#

您需要使用消息转换器配置restTemplate。在您的配置中执行以下操作:

@Bean
    public RestOperations restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

        
        converter.setSupportedMediaTypes(
                Arrays.asList(new MediaType[]{MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM}));

        restTemplate.setMessageConverters(Arrays.asList(converter, new FormHttpMessageConverter()));
        return restTemplate;
    }
jpfvwuh4

jpfvwuh42#

我想更好的解决方案是添加另一个转换器,而不是修改现有的转换器:

@Bean
public RestTemplate restTemplate() {
    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(jacksonSupportsMoreTypes());
    return restTemplate;
}

private HttpMessageConverter jacksonSupportsMoreTypes() {//eg. Gitlab returns JSON as plain text 
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaType.parseMediaType("text/plain;charset=utf-8"), MediaType.APPLICATION_OCTET_STREAM));
    return converter;
}
eulz3vhy

eulz3vhy3#

这两个答案对我都不起作用,尽管我没有尝试很长时间。这个解决方案不直接Map到POJO,而是用一行额外的代码解决了这个问题。
我通过改变

ResponseEntity<AbInitioResponse> responseEntity = restTemplate.exchange(urlTemplate, HttpMethod.GET, requestEntity, AbInitioResponse.class, params);
    AbInitioResponse abInitioResponse = responseEntity.getBody();

转换为以下类(以byte[]的形式获取响应,然后显式地将其序列化为所需的类

ResponseEntity<byte[]> responseEntity = restTemplate.exchange(urlTemplate, HttpMethod.GET, requestEntity, byte[].class, params);
    byte[] abInitioOctetResponse = responseEntity.getBody();
    AbInitioResponse abInitioResponse = objectMapper.readValue(abInitioOctetResponse, AbInitioResponse.class);

其中objectMapper是一个
download-file-of-content-type-octet-stream-using-resttemplate帮助了这个答案。

相关问题