RestTemplate報錯400 Bad Request的解決方案
RestTemplate報錯400 Bad Request
使用RestTemplate發(fā)送http請求,發(fā)現(xiàn)報錯400 Bad Request,其實這是個很基礎的問題,一般都能繞過去,像我這樣直接復制代碼才有可能發(fā)生這樣的錯誤情況。
先上原碼:
@Autowired
RestTemplate restTemplate;
public boolean alarm(String url,String body) {
if (body == null || url == null) {
return false;
}
try {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
HttpEntity<String> entity = new HttpEntity<>(body, httpHeaders);
FeishuAlarmResp result = restTemplate.postForObject(url, entity, FeishuAlarmResp.class);
if (result == null || result.getStatusCode() == null || result.getStatusCode() != 0) {
log.error("http發(fā)送失敗>>>>>>result={} message={}",JSON.toJSONString(result),body);
return false;
}
} catch (Throwable t) {
log.error("http發(fā)送異常:url:" + url + ",body:" + body, t);
return false;
}
return true;
}直接報錯:
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
問題所在
不能直接使用 @Autowired 自動注入 RestTemplate 使用。
因為,官網(wǎng)文檔有寫:
Since RestTemplate instances often need to be customized before being used, Spring Boot does not provide any single auto-configured RestTemplate bean.
(由于RestTemplate實例在使用前通常需要定制,Spring Boot不提供任何單個自動配置的RestTemplate bean。)
解決辦法
自定義RestTemplate的Bean對象,重點是要用restTemplateBuilder.build()來創(chuàng)建對象。
方法1
@Autowired
private RestTemplateBuilder restTemplateBuilder;
@Autowired
private RestTemplate restTemplate;
@Bean
public RestTemplate getRestTemplate() {
return restTemplateBuilder.build();
}
//調用方式:
String baiduHtml = restTemplate.getForObject("https://www.baidu.com", String.class);
System.out.println(baiduHtml);方法2:寫個config類
然后就可以用 @Autowired 自動注入 RestTemplate 使用了。
@Component
public class RestTemplateConfig {
/**
* RestTemplate
* @return RestTemplate
*/
@Bean
public RestTemplate restTemplate() {
return getRestTemplate();
}
/**
* 獲取自定義 RestTemplate
* @return RestTemplate
*/
private RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplateBuilder()
.setConnectTimeout(5 * 1000)
.setReadTimeout(60 * 1000)
.build();
// 為避免漢字變成問號,將String轉換器編碼格式置為 UTF-8
restTemplate.getMessageConverters().forEach(converter -> {
if (converter instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
}
});
return restTemplate;
}
}總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
java.lang.NumberFormatException異常解決方案詳解
這篇文章主要介紹了java.lang.NumberFormatException異常解決方案詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08
Java二維數(shù)組實現(xiàn)數(shù)字拼圖效果
這篇文章主要為大家詳細介紹了Java二維數(shù)組實現(xiàn)數(shù)字拼圖效果,控制臺可以對空格進行移動,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07
Java遞歸算法經(jīng)典實例(經(jīng)典兔子問題)
本文主要對經(jīng)典的兔子案例分析,來進一步更好的理解和學習java遞歸算法,具有很好的參考價值,需要的朋友一起來看下吧2016-12-12

