hotool工具类包
引入maven
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-http</artifactId> <version>${hutool.version}</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-core</artifactId> <version>${hutool.version}</version> </dependency>
http
获取网络图片的byte数组
String url = "https://img.yzcdn.cn/upload_files/2019/11/04/FkKxYNaJw26i906ze8SUIx4BRjlt.jpg";
//获取图片的byte数组 byte[] bytes = HttpRequest.get(url).timeout(20000).execute().bodyBytes();
//转换为base64字符串
String str= Base64Utils.encodeToString(bytes);
Controller
返回byte[],转成图片produces = MediaType.IMAGE_JPEG_VALUE
@GetMapping(value = "/pic", produces = MediaType.IMAGE_JPEG_VALUE) public byte[] getAImg(@Valid @RequestParam(value = "goods_spu_id") Long goodsSpuId, @ApiIgnore UserInfo userInfo) {
get请求写法
注解@RequestParam
value路径参数名
required是否必填
注解@Valid参数效验
注解@NotNull不能为null
注解@ApiIgnore忽略不用传的参数
swagger注解:@ApiParam(value=参数的描述,required=是否必传)
@GetMapping("/getByid")
public String getById(@RequestParam(value = "id",required = true)
@ApiParam(value = "id",required = true)
@Valid @NotNull(message = "id不能为空") Long id, @ApiIgnore UserInfo userInfo) {
jsckson配置
定义返回实体Data类型统一格式
定义返回的数字类型为String(原因:Long类型超过16位,前端js会丢失精度)
spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 generator: write_numbers_as_strings: true
在springboot项目中还可以使用如下代码(Long类型转换为String)
@Configuration public class JacksonConfig { /** * Jackson全局转化long类型为String,解决jackson序列化时long类型缺失精度问题 * @return Jackson2ObjectMapperBuilderCustomizer 注入的对象 */ @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { Jackson2ObjectMapperBuilderCustomizer cunstomizer = (builder)->builder.serializerByType(Long.TYPE, ToStringSerializer.instance).serializerByType(Long.class, ToStringSerializer.instance); return cunstomizer; } }