Http请求的响应没有Content-Length,只有Transfer-Encoding→chunked

如题:Http请求的响应没有Content-Length,只有Transfer-Encoding→chunked。如图

原因猜测:如果请求的响应返回是某个对象,则不会显示Content-Length,而显示Transfer-Encoding→chunked

如果请求的响应返回是简单类型(我亲测String)则会显示Content-Length 但是这里面有一个前提

server.compression.enabled=true
server.compression.min-response-size=204800 (就是属性很重要)
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain

解决办法:

1.将返回的对象通过JSON的   String s=JSONObject.toJSONString(obj);得到字符串类型;然后返回即可。

注意:但是此时返回的Content-Type →text/plain;charset=UTF-8,而不是Content-Type →application/json;charset=UTF-8(其实返回类型影响不大)

2.如图,通过response.getWrite().print();

  @GetMapping("/order/{id}")
    public void getOrder(@PathVariable String id, HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        String str = "product id ::product id :";
        try {
            response.getWriter().print(str);

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

 

3 将复杂对象转换统一转换

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.ArrayList;
import java.util.List;


/**
 * @author shihongxing
 * @since 2018-10-08 19:34
 */
@SpringBootApplication
public class SpringBootdemoApplication extends WebMvcConfigurerAdapter {
    public static void main(String[] args) {

        SpringApplication.run(SpringBootdemoApplication.class, args);
    }
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        //1.需要定义一个convert转换消息的对象;
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        //2.添加fastJson的配置信息,比如:是否要格式化返回的json数据;
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //3处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        //4.在convert中添加配置信息.
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        //5.将convert添加到converters当中.
        converters.add(fastJsonHttpMessageConverter);
    }
}

 

posted @ 2018-11-05 20:11  史红星-shihongxing  阅读(4950)  评论(0编辑  收藏  举报