整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

被坑过后才知道HttpMessageConverte

被坑过后才知道HttpMessageConverter多重要

、HttpMessageConverter简介

或许HttpMessageConverter没听过,但是@RequestBody和@ResponseBody这两个注解不会不知道吧,深入研究数据转换时,就会发现HttpMessageConverter这个接口,简单说就是HTTP的request和response的转换器,在遇到@RequestBody时候SpringBoot会选择一个合适的HttpMessageConverter实现类来进行转换,内部有很多实现类,也可以自己实现,如果这个实现类能处理这个数据,那么它的canRead()方法会返回true,SpringBoot会调用它的read()方法从请求中读出并转换成实体类,同样canWrite也是。

但是我并不是从这里认识到HttpMessageConverter的,而是从RestTemplate,RestTemplate是一个使用同步方式执行HTTP请求的类,因此不需要加入OkHttp或者其他HTTP客户端的依赖,使用它就可以和其他服务进行通信,但是容易出现转换问题,如果对微信接口或者qq接口有所了解的话,那么在使用RestTemplate调用他们服务的时候,必定会报一个错误。

如下面在调用qq互联获取用户信息的接口时,报的错误。

org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class xxx.xxx.xxxxx] and content type [text/html;charset=utf-8]
复制代码

错误信息是未知的ContentType,这个ContentType就是第三方接口返回时候在HTTP头中的Content-Type,如果通过其他工具查看这个接口返回的HTTP头,会发现它的值是text/html,通常我们见的都是application/json类型。(微信接口返回的是text/plain),由于内部没有HttpMessageConverter能处理text/html的数据,没有一个实现类的canRead()返回true,所以最后报错。


通常使用OkHttp或者其他框架时不会遇到这个错误。

二、深入报错源码

只有了解了报错原因以及源码,才能更好的解决问题,所以,我们根据报错源码的行数,定位到HttpMessageConverterExtractor下的extractData方法,从这个结构一眼就能看出大概逻辑:循环找出能处理这个contentType的HttpMessageConverter,然后调用这个HttpMessageConverter的read()并返回。

 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;
                     //判断这个转换器是不能能转换这个类型
                     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能进行转换,则调用read并返回
                         return genericMessageConverter.read(this.responseType, (Class)null, responseWrapper);
                     }
                 }
                 //还是判断这个转换器能不能进行转换
                 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能进行转换,则调用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);
         }
         //走到这抛出异常,所有的消息转换器都不能进行处理。
         throw new UnknownContentTypeException(this.responseType, contentType, response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), getResponseBody(response));
     } else {
         return null;
     }
 }
复制代码

messageConverters集合中就保存着在RestTemplate构造方法中添加的HttpMessageConverter实现类。

三、自定义HttpMessageConverter

找到了原因,我们就需要解决问题,下面使用一个简单的办法,即重新设置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转换类,但是他不能处理text/html的数据,原因是他的父类AbstractHttpMessageConverter中的supportedMediaTypes集合中没有text/html类型,如果有的话就能处理了,通过setSupportedMediaTypes可以给他指定一个新的MediaType集合,上面的写法会导致MappingJackson2HttpMessageConverter只能处理text/html类型的数据。

但是,为了更深的研究,我们要直接继承HttpMessageConverter(当然更推荐的是继承AbstractHttpMessageConverter)来实现,在此之前,先看这几个方法具体代表什么意思,才能继续往下写。

public interface HttpMessageConverter<T> {
    /**
     * 根据mediaType判断clazz是否可读
     */
    boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);

    /**
     * 根据mediaType判断clazz是否可写
     */
    boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);

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

    /**
     * 将HttpInputMessage流中的数据绑定到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就会调用read,用来将字节流中的数据转换成具体实体,aClass就是我们最终想要得到的实例对象的Class,StreamUtils这个工具类是SpringBoot自带的一个,用来读取InputStream中的数据并返回String字符串,SpringBoott内部很多地方都用到了这个工具类,所以这里来借用一下,现在拿到了String型的数据后,就需要将String转换成对应的对象,这里可能想到了Gson、Fastjson,使用他们也可以完成,但是还需要额外的加入jar包,SpringBoot自身已经集成了ObjectMapper,所以在来借用一下。

package com.hxl.vote.config;

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()会返回现有的HttpMessageConverter集合,我们在这个基础上加入我们自定义的HttpMessageConverter即可,这回就不报错了。

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

继承AbstractHttpMessageConverter

AbstractHttpMessageConverter帮我们封装了一部分事情,但是有些事情是他不能确定的,所以要交给子类实现,使用以下方法,同样可以解决text/html的问题。

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 {
    }
}
复制代码

继承MappingJackson2HttpMessageConverter

好吧,使用MappingJackson2HttpMessageConverter,只需要给他能处理的MediaType即可,更简单。

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


作者:i听风逝夜
链接:https://juejin.im/post/6886733763020062733
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

页可见区域宽:document.body.clientWidth

网页可见区域高:document.body.clientHeight

网页可见区域宽:document.body.offsetWidth (包括边线的宽)

网页可见区域高:document.body.offsetHeight (包括边线的宽)

网页正文全文宽:document.body.scrollWidth

网页正文全文高:document.body.scrollHeight

网页被卷去的高:document.body.scrollTop

网页被卷去的左:document.body.scrollLeft

网页正文部分上:window.screenTop

网页正文部分左:window.screenLeft

屏幕分辨率的高:window.screen.height

屏幕分辨率的宽:window.screen.width

屏幕可用工作区高度:window.screen.availHeight

屏幕可用工作区宽度:window.screen.availWidth

HTML精确定位:scrollLeft,scrollWidth,clientWidth,offsetWidth

scrollHeight: 获取对象的滚动高度。

scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离

scrollTop:设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离

scrollWidth:获取对象的滚动宽度

offsetHeight:获取对象相对于版面或由父坐标 offsetParent 属性指定的父坐标的高度

offsetLeft:获取对象相对于版面或由 offsetParent 属性指定的父坐标的计算左侧位置

offsetTop:获取对象相对于版面或由 offsetTop 属性指定的父坐标的计算顶端位置

event.clientX 相对文档的水平座标

event.clientY 相对文档的垂直座标

event.offsetX 相对容器的水平坐标

event.offsetY 相对容器的垂直坐标

document.documentElement.scrollTop 垂直方向滚动的值

event.clientX+document.documentElement.scrollTop 相对文档的水平座标+垂直方向滚动的量

IE,FireFox 差异如下:

IE6.0、FF1.06+:

clientWidth=width + padding

clientHeight=height + padding

offsetWidth=width + padding + border

offsetHeight=height + padding + border

IE5.0/5.5:

clientWidth=width - border

clientHeight=height - border

offsetWidth=width

offsetHeight=height

(需要提一下:CSS中的margin属性,与clientWidth、offsetWidth、clientHeight、offsetHeight均无关)

网页可见区域宽: document.body.clientWidth

网页可见区域高: document.body.clientHeight

网页可见区域宽: document.body.offsetWidth (包括边线的宽)

网页可见区域高: document.body.offsetHeight (包括边线的高)

网页正文全文宽: document.body.scrollWidth

网页正文全文高: document.body.scrollHeight

网页被卷去的高: document.body.scrollTop

网页被卷去的左: document.body.scrollLeft

网页正文部分上: window.screenTop

网页正文部分左: window.screenLeft

屏幕分辨率的高: window.screen.height

屏幕分辨率的宽: window.screen.width

屏幕可用工作区高度: window.screen.availHeight

屏幕可用工作区宽度: window.screen.availWidth

-------------------

技术要点

本节代码主要使用了Document对象关于窗口的一些属性,这些属性的主要功能和用法如下。

要得到窗口的尺寸,对于不同的浏览器,需要使用不同的属性和方法:若要检测窗口的真实尺寸,在Netscape下需要使用Window的属性;在IE下需要 深入Document内部对body进行检测;在DOM环境下,若要得到窗口的尺寸,需要注意根元素的尺寸,而不是元素。

Window对象的innerWidth属性包含当前窗口的内部宽度。Window对象的innerHeight属性包含当前窗口的内部高度。

Document对象的body属性对应HTML文档的标签。Document对象的documentElement属性则表示HTML文档的根节点。

document.body.clientHeight表示HTML文档所在窗口的当前高度。document.body. clientWidth表示HTML文档所在窗口的当前宽度。

实现代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>请调整浏览器窗口</title>

<meta http-equiv="content-type" content="text/html; charset=gb2312">

</head>

<body>

<h2 align="center">请调整浏览器窗口大小</h2><hr>

<form action="#" method="get" name="form1" id="form1">

<!--显示浏览器窗口的实际尺寸-->

浏览器窗口 的 实际高度: <input type="text" name="availHeight" size="4"><br>

浏览器窗口 的 实际宽度: <input type="text" name="availWidth" size="4"><br>

</form>

<script type="text/javascript">

<!--

var winWidth=0;

var winHeight=0;

function findDimensions() //函数:获取尺寸

{

//获取窗口宽度

if (window.innerWidth)

winWidth=window.innerWidth;

else if ((document.body) && (document.body.clientWidth))

winWidth=document.body.clientWidth;

//获取窗口高度

if (window.innerHeight)

winHeight=window.innerHeight;

else if ((document.body) && (document.body.clientHeight))

winHeight=document.body.clientHeight;

//通过深入Document内部对body进行检测,获取窗口大小

if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth)

{

winHeight=document.documentElement.clientHeight;

winWidth=document.documentElement.clientWidth;

}

//结果输出至两个文本框

document.form1.availHeight.value=winHeight;

document.form1.availWidth.value=winWidth;

}

findDimensions();

//调用函数,获取数值

window.onresize=findDimensions;

//-->

</script>

</body>

</html>

源程序解读

(1)程序首先建立一个表单,包含两个文本框,用于显示窗口当前的宽度和高度,并且,其数值会随窗口大小的改变而变化。

(2)在随后的JavaScript代码中,首先定义了两个变量winWidth和winHeight,用于保存窗口的高度值和宽度值。

(3)然后,在函数findDimensions ( )中,使用window.innerHeight和window.innerWidth得到窗口的高度和宽度,并将二者保存在前述两个变量中。

(4)再通过深入Document内部对body进行检测,获取窗口大小,并存储在前述两个变量中。

(5)在函数的最后,通过按名称访问表单元素,结果输出至两个文本框。

(6)在JavaScript代码的最后,通过调用findDimensions ( )函数,完成整个操作。

带有两个输入字段和一个提交按钮的 HTML 表单:

<form action="demo_form.php" method="get">

First name: <input type="text" name="fname"><br>

Last name: <input type="text" name="lname"><br>

<input type="submit" value="提交">

</form>

(更多实例见页面底部)


浏览器支持

所有主流浏览器都支持 <form> 标签。


标签定义及使用说明

<form> 标签用于创建供用户输入的 HTML 表单。

<form> 元素包含一个或多个如下的表单元素:

  • <input>

  • <textarea>

  • <button>

  • <select>

  • <option>

  • <optgroup>

  • <fieldset>

  • <label>


HTML 4.01 与 HTML5之间的差异

HTML5 新增了两个新的属性:autocomplete 和 novalidate,同时不再支持 HTML 4.01 中的某些属性。


HTML 与 XHTML 之间的差异

在 XHTML 中,name 属性已被废弃。使用全局 id 属性代替。


属性

New :HTML5 中的新属性。

属性描述
acceptMIME_typeHTML5 不支持。规定服务器接收到的文件的类型。(文件是通过文件上传提交的)
accept-charsetcharacter_set规定服务器可处理的表单数据字符集。
actionURL规定当提交表单时向何处发送表单数据。
autocompleteNewonoff规定是否启用表单的自动完成功能。
enctypeapplication/x-www-form-urlencodedmultipart/form-datatext/plain规定在向服务器发送表单数据之前如何对其进行编码。(适用于 method="post" 的情况)
methodgetpost规定用于发送表单数据的 HTTP 方法。
nametext规定表单的名称。
novalidateNewnovalidate如果使用该属性,则提交表单时不进行验证。
target_blank_self_parent_top规定在何处打开 action URL。

全局属性

<form> 标签支持 HTML 的全局属性。


事件属性

<form> 标签支持 HTML 的事件属性。

实例

带有复选框的表单

此表单包含两个复选框和一个提交按钮。

带有单选按钮的表单

此表单包含两个单选框和一个提交按钮。

如您还有不明白的可以在下面与我留言或是与我探讨QQ群308855039,我们一起飞!