国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Could not extract response: no suitable HttpMessageConverter found for content type [text/html]

這篇具有很好參考價值的文章主要介紹了Could not extract response: no suitable HttpMessageConverter found for content type [text/html]。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。


如果是使用 OpenFeign 進行遠程調(diào)用的時候,報以下錯誤 no suitable HttpMessageConverter

可考慮修改 feign 接口,如下,使用注解 @ResponseBody、@RequestBody

@FeignClient("gulimall-order")
public interface OrderFeignService {
    @RequestMapping("/order/order/listWithItem")
    @ResponseBody
    R listWithItem(@RequestBody Map<String, Object> params);
}

報錯信息

在使用 RestTemplate請求調(diào)用的時候,程序報錯

報錯信息如下:

org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class afei.common.utils.R] and content type [text/html;charset=UTF-8]
	at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:121) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
	at org.springframework.cloud.openfeign.support.SpringDecoder.decode(SpringDecoder.java:59) ~[spring-cloud-openfeign-core-2.1.3.RELEASE.jar:2.1.3.RELEASE]
	at org.springframework.cloud.openfeign.support.ResponseEntityDecoder.decode(ResponseEntityDecoder.java:62) ~[spring-cloud-openfeign-core-2.1.3.RELEASE.jar:2.1.3.RELEASE]
	at feign.optionals.OptionalDecoder.decode(OptionalDecoder.java:36) ~[feign-core-10.2.3.jar:na]

錯誤信息是未知的ContentType,這個ContentType就是第三方接口返回時候在HTTP頭中的Content-Type,如果通過其他工具查看這個接口返回的HTTP頭,會發(fā)現(xiàn)他的值是 text/html,通常我們見的都是 application/json 類型。(微信接口返回的是text/plain),由于內(nèi)部沒有 HttpMessageConverter 能處理text/html的數(shù)據(jù),沒有一個實現(xiàn)類的 canRead() 返回 true,所以最后報錯

Could not extract response: no suitable HttpMessageConverter found for content type [text/html]

源碼分析

public T extractData(ClientHttpResponse response) throws IOException {
    MessageBodyClientHttpResponseWrapper responseWrapper = new MessageBodyClientHttpResponseWrapper(response);
    if (responseWrapper.hasMessageBody() && !responseWrapper.hasEmptyMessageBody()) {
        MediaType contentType = this.getContentType(responseWrapper);
        try {
        	//拿到messageConverters的迭代器
            Iterator var4 = this.messageConverters.iterator();
            while(var4.hasNext()) {
            	//下一個HttpMessageConverter
                HttpMessageConverter<?> messageConverter = (HttpMessageConverter)var4.next();
                //如果是GenericHttpMessageConverter接口的實例,繼承AbstractHttpMessageConverter會走這個if。
                if (messageConverter instanceof GenericHttpMessageConverter) {
                    GenericHttpMessageConverter<?> genericMessageConverter = (GenericHttpMessageConverter)messageConverter;
                    //判斷這個轉(zhuǎn)換器能不能轉(zhuǎn)換這個contentType類型
                    if (genericMessageConverter.canRead(this.responseType, (Class)null, contentType)) {
                        if (this.logger.isDebugEnabled()) {
                            ResolvableType resolvableType = ResolvableType.forType(this.responseType);
                            this.logger.debug("Reading to [" + resolvableType + "]");
                        }
                        //走到這代表當前的HttpMessageConverter能進行轉(zhuǎn)換,則調(diào)用read并返回
                        return genericMessageConverter.read(this.responseType, (Class)null, responseWrapper);
                    }
                }
                //還是判斷這個轉(zhuǎn)換器能不能進行contentType轉(zhuǎn)換
                if (this.responseClass != null && messageConverter.canRead(this.responseClass, contentType)) {
                    if (this.logger.isDebugEnabled()) {
                        String className = this.responseClass.getName();
                        this.logger.debug("Reading to [" + className + "] as \"" + contentType + "\"");
                    }
                    //走到這代表當前的HttpMessageConverter能進行轉(zhuǎn)換,則調(diào)用read并返回
                    return messageConverter.read(this.responseClass, responseWrapper);
                }
            }
        } catch (HttpMessageNotReadableException | IOException var8) {
            throw new RestClientException("Error while extracting response for type [" + this.responseType + "] and content type [" + contentType + "]", var8);
        }
        //走到這拋出異常,所有的消息轉(zhuǎn)換器都不能進行處理。
        throw new UnknownContentTypeException(this.responseType, contentType, response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), getResponseBody(response));
    } else {
        return null;
    }
}

messageConverters 集合中就保存著
在 RestTemplate 構(gòu)造方法中添加的 HttpMessageConverter 實現(xiàn)類

Could not extract response: no suitable HttpMessageConverter found for content type [text/html]

解決方法

修改 mappingJackson2HttpMessageConverter 配置

重新設(shè)置 MappingJackson2HttpMessageConverter 能處理的 MediaType

@Bean
public RestTemplate restTemplate(){
    RestTemplate restTemplate = new RestTemplate();
    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_HTML));
    restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter);
    return  restTemplate;
}

MappingJackson2HttpMessageConverter 也是一個 HttpMessageConverter 轉(zhuǎn)換類,但是他不能處理 text/html 的數(shù)據(jù),原因是他的父類 AbstractHttpMessageConverter 中的 supportedMediaTypes 集合中沒有 text/html 類型,如果有的話就能處理了,通過 setSupportedMediaTypes 可以給他指定一個新的 MediaType 集合

上面的寫法會導(dǎo)致 MappingJackson2HttpMessageConverter 只能處理 text/html 類型的數(shù)據(jù)

繼承 mappingJackson2HttpMessageConverter

使用MappingJackson2HttpMessageConverter,只需要給他能處理的MediaType

public class QQHttpMessageConverter extends MappingJackson2HttpMessageConverter {
    public QQHttpMessageConverter() {
        setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_HTML));
    }
}

然后將這個消息轉(zhuǎn)換器追加到RestTemplate中的 messageConverters

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new QQHttpMessageConverter());  // 兼容 text/plain
    return restTemplate;
}

實現(xiàn) HttpMessageConverter

直接繼承HttpMessageConverter(當然更推薦的是繼承 Abstract HttpMessageConverter)來實現(xiàn)

public interface HttpMessageConverter<T> {
    /**
     * 根據(jù)mediaType判斷clazz是否可讀
     */
    boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);

    /**
     * 根據(jù)mediaType判斷clazz是否可寫
     */
    boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);

    /**
     * 獲取支持的mediaType
     */
    List<MediaType> getSupportedMediaTypes();

    /**
     * 將HttpInputMessage流中的數(shù)據(jù)綁定到clazz中
     */
    T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException;

    /**
     * 將t對象寫入到HttpOutputMessage流中
     */
    void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException;
}

canWrite,write方式是不需要處理的,只管canRead和read就行

在 canRead 方法中判斷了是不是 text/html 類型,是的話就會返回true,Spring 就會調(diào)用 read,用來將字節(jié)流中的數(shù)據(jù)轉(zhuǎn)換成具體實體,aClass就是我們最終想要得到的實例對象的Class

StreamUtils 這個工具類是SpringBoot自帶的一個,用來讀取InputStream中的數(shù)據(jù)并返回String字符串,SpringBoott內(nèi)部很多地方都用到了這個工具類

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;

public class QQHttpMessageConverter implements HttpMessageConverter<Object> {
    @Override
    public boolean canRead(Class<?> aClass, MediaType mediaType) {
        if (mediaType != null) {
            return mediaType.isCompatibleWith(MediaType.TEXT_HTML);
        }
        return false;
    }

    @Override
    public boolean canWrite(Class<?> aClass, MediaType mediaType) {
        return false;
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return Arrays.asList(MediaType.TEXT_HTML);
    }

    @Override
    public Object read(Class<?> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        String json = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("UTF-8"));
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper.readValue(json, aClass);
    }

    @Override
    public void write(Object o, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {

    }
}

最后需要要進行配置,getMessageConverters() 會返回現(xiàn)有的 HttpMessageConverter 集合,我們在這個基礎(chǔ)上加入我們自定義的 HttpMessageConverter 即可文章來源地址http://www.zghlxwxcb.cn/news/detail-477165.html

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

繼承 AbstractHttpMessageConverter

public class QQHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
    public QQHttpMessageConverter() {
        super(MediaType.TEXT_HTML);
    }
    @Override
    protected boolean supports(Class<?> aClass) {
        return true;
    }
    @Override
    protected Object readInternal(Class<?> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        String json = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.forName("UTF-8"));
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper.readValue(json, aClass);
    }
    @Override
    protected void writeInternal(Object o, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
    }
}

到了這里,關(guān)于Could not extract response: no suitable HttpMessageConverter found for content type [text/html]的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 互聯(lián)網(wǎng)大廠技術(shù)-HTTP請求-Springboot整合Feign更優(yōu)雅地實現(xiàn)Http服務(wù)調(diào)用
no suitable HttpMessageConverter found for response type

    互聯(lián)網(wǎng)大廠技術(shù)-HTTP請求-Springboot整合Feign更優(yōu)雅地實現(xiàn)Http服務(wù)調(diào)用 no suitable HttpMessageConverter found for response type

    目錄 一、SpringBoot快速整合Feign 1.添加Pom依賴 2.啟動類添加注解 3.引用Feign服務(wù) 二、為請求添加Header的3種方式 1.添加固定header 2.通過接口簽名添加header 3.動態(tài)添加header 三、為請求添加超時配置 1.默認超時時間 3.超時異常 4.全局超時配置 5.為單個服務(wù)設(shè)置超時配置 四、為請求配

    2024年02月11日
    瀏覽(23)
  • Could not autowire. No beans of ‘DiscoveryClient‘ type found.

    Could not autowire. No beans of ‘DiscoveryClient‘ type found.

    一、導(dǎo)錯了包 DiscoveryClient對應(yīng)有兩個包: org.springframework.cloud.client.discovery.DiscoveryClient; com.netflix.discovery.DiscoveryClient; 目前導(dǎo)入的包是: 改成第一個包,發(fā)現(xiàn)不再報紅了。

    2024年02月11日
    瀏覽(30)
  • @Autowired報錯Could not autowire. No beans of ‘XXX‘ type found

    @Autowired報錯Could not autowire. No beans of ‘XXX‘ type found

    ??IDEA中使用 @Autowired 報錯 Could not autowire. No beans of \\\'XXX\\\' type found ,錯誤大致意思為:沒有匹配到類型為XXX的bean。 ??個人覺得,注入 controller 的 service 雖然一般來說我們都是注入一個接口,但是該接口有實現(xiàn)類,并且使用 @Service 進行關(guān)聯(lián),所以注入類型應(yīng)該也可以視為一

    2024年02月07日
    瀏覽(26)
  • idea報錯:Could not autowire. No beans of ‘UserService‘ type found.

    點個關(guān)注,必回關(guān) 翻譯:無法自動連線。未找到“用戶服務(wù)”類型的服務(wù)類。 當報錯之后idea會提示錯誤,不過程序的編譯和運行都是沒有問題的(這個錯誤提示不會產(chǎn)生任何印象) 解決方案 解決方案1: Settings - Editor - Inspections - Spring - Spring Core - Code - Autowiring for Bean Class

    2024年02月11日
    瀏覽(24)
  • idea報“Could not autowire. No beans of ‘UserMapper‘ type found. ”錯解決辦法

    idea報“Could not autowire. No beans of ‘UserMapper‘ type found. ”錯解決辦法

    idea具有檢測功能,接口不能直接創(chuàng)建bean的,需要用動態(tài)代理技術(shù)來解決。 1.修改idea的配置 1.點擊file,選擇setting 2.搜索inspections,找到Spring 3.找到Spring子目錄下的Springcore 4.在Springcore的子目錄下找到code 5.把seyerity選項改成警告 2.修改代碼 1,@Autowrited改為@Autowrited(required = false)

    2024年02月05日
    瀏覽(26)
  • IDEA提示找不到Mapper接口:Could not autowire.No beans of ‘xxxMapper‘ type found

    IDEA提示找不到Mapper接口:Could not autowire.No beans of ‘xxxMapper‘ type found

    我們可以看到,上面的紅色警告在提示我們,找不到 xxxMaper 這個類型的 bean。 為啥呢? 因為 @Mapper 這個注解是 Mybatis 提供的,而 @Autowried 注解是 Spring 提供的,IDEA能理解 Spring 的上下文,但是卻和 Mybatis 關(guān)聯(lián)不上。而且我們可以根據(jù) @Autowried 源碼看到,默認情況下,@Autowri

    2024年02月08日
    瀏覽(24)
  • 解決SpringBoot項目中的報錯:Could not autowire,no beans of “XXX“ type found

    解決SpringBoot項目中的報錯:Could not autowire,no beans of “XXX“ type found

    問題:找不到mapper注入的bean,如圖 ? 分析:注入mapper有兩種方式: ?第一種:在啟動類中添加? @MapperScan ???????然后在mapper的類中添加? @Repository 注解 第二種方法:直接在各個mapper類中添加@Mapper注解,但是一定要注意導(dǎo)入正確的包,否則解決不了這個異常; ?很多新手

    2024年02月08日
    瀏覽(33)
  • SpringBoot - 在IDEA中經(jīng)常發(fā)現(xiàn):Could not autowire. No beans of ‘xxx‘ type found的錯誤

    SpringBoot - 在IDEA中經(jīng)常發(fā)現(xiàn):Could not autowire. No beans of ‘xxx‘ type found的錯誤

    錯誤描述 在SPRINGBOOT的項目中,使用IDEA時經(jīng)常會遇到Could not autowire. No beans of ‘xxxx’ type found的錯誤提示,但是程序的編譯和運行都沒有問題,這個錯誤提示并不影響項目的生產(chǎn)。 解決方案

    2024年02月15日
    瀏覽(23)
  • Qt創(chuàng)建控制臺程序選擇構(gòu)建套件問題“No suitable kits found”

    Qt創(chuàng)建控制臺程序選擇構(gòu)建套件問題“No suitable kits found”

    QT 選擇構(gòu)建套件時出現(xiàn)問題: “No suitable kits found” = 沒有找到合適的kits套件,在安裝Qt Creator時沒有安裝MinGW,所以只需要進行安裝即可。 3.1 選擇安裝目錄下的“MaintenanceTool.exe”,雙擊計入組件安裝界面。 3.2 點擊“下一步” 3.3 選擇“添加或移除組件”: 3.4 根據(jù)自己安裝

    2024年02月11日
    瀏覽(21)
  • 已解決No suitable driver found for jdbc:mysql://localhost:3306/ 問題

    已解決No suitable driver found for jdbc:mysql://localhost:3306/ 問題

    已解決No suitable driver found for jdbc:mysql://localhost:3306/ 問題 在學(xué)習java數(shù)據(jù)庫連接池使用的時候遇到問題,無法連接到數(shù)據(jù)庫,查看日志是\\\"No Suitable Driver Found For Jdbc\\\",但查看數(shù)據(jù)庫連接配置沒問題。 這個問題可把我愁壞了,要不問一下GPT?上。 問了一下GPT,得到的答案是這樣的

    2024年02月07日
    瀏覽(28)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包