1. 程式人生 > 實用技巧 >restTemplate 401 Unauthorized: [no body]

restTemplate 401 Unauthorized: [no body]

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; }