springboot 使用restTemplate發送post請求,傳json數據,結果報錯401 Unauthorized: [no body]
添加相應的數據格式就解決了
@Bean public RestTemplate registerTemplate() { RestTemplate restTemplate = new RestTemplate(getFactory()); //這個地方需要配置消息轉換器,不然收到消息后轉換會出現異常 restTemplate.setMessageConverters(getConverts()); return restTemplate; } private SimpleClientHttpRequestFactory getFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(connectionTimeout); factory.setReadTimeout(readTimeout); return factory; } private List<HttpMessageConverter<?>> getConverts() { List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); // String轉換器 StringHttpMessageConverter stringConvert = new StringHttpMessageConverter(); List<MediaType> stringMediaTypes = new ArrayList<MediaType>() {{ //添加響應數據格式,不匹配會報401 add(MediaType.TEXT_PLAIN); add(MediaType.TEXT_HTML); add(MediaType.APPLICATION_JSON); }}; stringConvert.setSupportedMediaTypes(stringMediaTypes); messageConverters.add(stringConvert); return messageConverters; }