Browse Source

完善消息转换

killua 5 years ago
parent
commit
3cb5e85bf2
1 changed files with 45 additions and 1 deletions
  1. 45 1
      source/_posts/HttpMessageConverter.md

+ 45 - 1
source/_posts/HttpMessageConverter.md

@@ -49,6 +49,7 @@ public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
      );
      fastConverter.setFastJsonConfig(fastJsonConfig);
      //将fastjson添加到视图消息转换器列表内
+     // converters.add(0, fastConverter); 可提高优先级
      converters.add(fastConverter);
  }
 ```
@@ -113,4 +114,47 @@ public HttpMessageConverters stringHttpMessageConverter() {
             Charset.forName("UTF-8"));
     return new HttpMessageConverters(converter);
 }
-``` 
+``` 
+
+### 自定义消息
+在某些特殊业务场景或者避免复杂冗余的重复,多平台请求方式不同兼容等都可通过自定义消息解析器优化
+```
+/**
+ * @author : wangzhiyong
+ * @date : 2019/1/25 15:30
+ * description : 系统自定义消息转换器
+ */
+public class CustomHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
+
+    CustomHttpMessageConverter() {
+        // 自定义请求类型解析
+        super(new MediaType("application", "dzdy", Charset.forName("UTF-8")));
+    }
+
+    @Override
+    protected boolean supports(Class<?> clazz) {
+        // 用于处理某特殊类或者true 全部类
+        return true;
+    }
+
+    @Override
+    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
+        // todo 特殊的加密或字符串解析
+        InputStream inputStream = inputMessage.getBody();
+        StringWriter writer = new StringWriter();
+        IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8.name());
+        String str = writer.toString();
+        return JSONObject.parseObject(str, clazz);
+    }
+
+    @Override
+    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
+        // todo 特殊的解密或字符串拼接
+        OutputStream outputStream = outputMessage.getBody();
+        IOUtils.write(JSONObject.toJSONString(o), outputStream, StandardCharsets.UTF_8.name());
+        outputStream.flush();
+        outputStream.close();
+    }
+}
+```
+eg. 请求对象需添加 @RequestBody 定义走mvc解析