如題: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); } }