一、定义类继承自AbstractHttpMessageConverter
package cn.edu.tju.config;
import cn.edu.tju.UserInfo;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
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.ArrayList;
import java.util.List;
public class MyHttpMessageConverter extends AbstractHttpMessageConverter<UserInfo> {
public MyHttpMessageConverter() {
super(new MediaType("application", "amadeus", Charset.forName("UTF-8")));
}
@Override
protected boolean supports(Class<?> clazz) {
return UserInfo.class.isAssignableFrom(clazz);
}
@Override
protected UserInfo readInternal(Class<? extends UserInfo> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
String temp = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
String[] stringArray = temp.split("-");
UserInfo userInfo= new UserInfo();
userInfo.setUsername(stringArray[0]);
userInfo.setPassword(stringArray[1]);
return userInfo;
}
@Override
protected void writeInternal(UserInfo userInfo, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
String stringToWrite=userInfo.getUsername()+":"+userInfo.getPassword();
outputMessage.getBody().write(stringToWrite.getBytes());
}
/* @Override
public List<MediaType> getSupportedMediaTypes(Class<?> clazz) {
MediaType mediaType = new MediaType("application", "amadeus", Charset.forName("UTF-8"));
List<MediaType> mediaTypeList=new ArrayList<>();
mediaTypeList.add(mediaType);
return mediaTypeList;
}*/
}
其中构造方法中super(new MediaType(“application”, “amadeus”, Charset.forName(“UTF-8”)));指定了要处理的请求头的类型为:
application/amadeus;charset=utf-8
二、将上述converter注册到Spring Mvc
package cn.edu.tju.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(converter());
}
@Bean
public MyHttpMessageConverter converter() {
return new MyHttpMessageConverter();
}
}
三、请求时设定请求头:
四、定义controller
@RequestMapping("/info4")
public UserInfo info4(@RequestBody UserInfo info) {
UserInfo userInfo=new UserInfo();
String prefix="[pre]";
userInfo.setUsername(prefix+info.getUsername());
userInfo.setPassword(prefix+info.getPassword());
return userInfo;
}
五、请求和响应: