SpringBoot RestTemplate請(qǐng)求日志打印方式
SpringBoot RestTemplate請(qǐng)求日志打印
RestTemplateConfig 配置
@Configuration
public class RestTemplateConfig {
/**
* 初始化連接工廠
* @return
*/
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
/**連接超時(shí)*/
factory.setConnectTimeout(15000);
/**讀超時(shí)*/
factory.setReadTimeout(5000);
return factory;
}
/**
* 初始化請(qǐng)求模板
* @param simpleClientHttpRequestFactory
* @return
*/
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory simpleClientHttpRequestFactory,@Qualifier("loggingRequestInterceptor") LoggingRequestInterceptor loggingRequestInterceptor){
RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(simpleClientHttpRequestFactory));
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(loggingRequestInterceptor);
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
/**
* 返回請(qǐng)求工具類
* @param restTemplate
* @return
*/
@Bean
public HttpRequestUtils getHttpRequestUtils(RestTemplate restTemplate){
HttpRequestUtils httpRequestUtils = new HttpRequestUtils();
httpRequestUtils.setRestTemplate(restTemplate);
return httpRequestUtils;
}
}HttpUtils 工具類
public class HttpUtils {
private RestTemplate restTemplate;
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
/**
* @param : url
* @description: post請(qǐng)求 get
*/
public String sendGetRequest(String url) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity httpEntity = new HttpEntity(headers);//請(qǐng)求體,包括請(qǐng)求數(shù)據(jù) body 和 請(qǐng)求頭 headers
ResponseEntity<String> strbody = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
return strbody.getBody();
}
/**
* @param : url
* @param : data
* @description: post請(qǐng)求 json
*/
public String sendPostRequest(String url, JSONObject data) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity httpEntity = new HttpEntity(data, headers);//請(qǐng)求體,包括請(qǐng)求數(shù)據(jù) body 和 請(qǐng)求頭 headers
ResponseEntity<String> strbody = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
return strbody.getBody();
}
/**
* @param : url
* @param : data
* @description: post請(qǐng)求 json
*/
public String sendPostRequest(String url, String data) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity httpEntity = new HttpEntity(data, headers);//請(qǐng)求體,包括請(qǐng)求數(shù)據(jù) body 和 請(qǐng)求頭 headers
ResponseEntity<String> strbody = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
return strbody.getBody();
}
}LoggingRequestInterceptor 攔截類
@Component("loggingRequestInterceptor")
public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {
Logger log = LoggerFactory.getLogger(getClass());
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
traceRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
traceResponse(response);
return response;
}
private void traceRequest(HttpRequest request, byte[] body) throws IOException {
log.debug("===========================request begin================================================");
log.debug("URI : {}", request.getURI());
log.debug("Method : {}", request.getMethod());
log.debug("Headers : {}", request.getHeaders() );
log.debug("Request body: {}", new String(body, "UTF-8"));
log.debug("==========================request end================================================");
}
private void traceResponse(ClientHttpResponse response) throws IOException {
StringBuilder inputStringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
String line = bufferedReader.readLine();
while (line != null) {
inputStringBuilder.append(line);
inputStringBuilder.append('\n');
line = bufferedReader.readLine();
}
log.debug("============================response begin==========================================");
log.debug("Status code : {}", response.getStatusCode());
log.debug("Status text : {}", response.getStatusText());
log.debug("Headers : {}", response.getHeaders());
log.debug("Response body: {}", inputStringBuilder.toString());
log.debug("=======================response end=================================================");
}
}關(guān)于springboot restTemplate傳文件爬坑
關(guān)于restTemplate post請(qǐng)求中包含文件類型
public void test5(){
? ? MultiValueMap param = new LinkedMultiValueMap();
? ? FileSystemResource ?file = new FileSystemResource("C:\\Users\\Ryan\\Postman\\files\\zm.png");
? ? param .add("image",file);
? ? ResponseEntity<String> idCardOcrRes = this.restTemplateForFile(idCardOCRUrl,param,String.class);
? ? String idCardOcrResBody = idCardOcrRes.getBody();
? ? System.out.println(idCardOcrResBody);
}
private <T> ResponseEntity<T> restTemplateForFile(String url, MultiValueMap<String,Object> map, Class<T> responseClass){
? ? //設(shè)置請(qǐng)求頭
? ? HttpHeaders headers = new HttpHeaders();
? ? MediaType mediaType = MediaType.parseMediaType("multipart/form-data");
? ? headers.setContentType(mediaType);
? ? //請(qǐng)求體為入?yún)ap
? ? //用httpEntity封裝整個(gè)請(qǐng)求報(bào)文
? ? HttpEntity<MultiValueMap<String,Object>> entity = new HttpEntity(map,headers);
? ? ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, entity, responseClass);
? ? return responseEntity;
}注意使用FileSystemResource類型的文件即可。
本人在過(guò)程中遇到過(guò)一個(gè)問(wèn)題,在此記錄下來(lái),param為MultiValueMap
logger.info("param:{},userNo:{},incomingNo:{}",JSONObject.toJSONString(param),userNo,incomingNo);若加入此日志輸出,會(huì)清空新建的文件,這個(gè)問(wèn)題困擾好久?。?!
關(guān)于restTemplate 響應(yīng)狀態(tài)碼捕捉
捕捉 RestClientResponseException e 類型異常,
int statis = e.getRawStatusCode(); String responseBodyAsString = e.getResponseBodyAsString();
可以得到具體的響應(yīng)消息以及響應(yīng)狀態(tài)碼
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)登錄密碼強(qiáng)度校驗(yàn)的項(xiàng)目實(shí)踐
本文主要介紹了Java實(shí)現(xiàn)登錄密碼強(qiáng)度校驗(yàn)的項(xiàng)目實(shí)踐,包括使用正則表達(dá)式匹配校驗(yàn)和密碼強(qiáng)度校驗(yàn)工具類這兩種方法,具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01
SpringBoot對(duì)接twilio實(shí)現(xiàn)郵件信息發(fā)送功能
這篇文章主要為大家詳細(xì)介紹了SpringBoot如何對(duì)接twilio實(shí)現(xiàn)郵件信息發(fā)送功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-03-03
java基礎(chǔ)之泛型知識(shí)點(diǎn)總結(jié)
這篇文章主要介紹了java基礎(chǔ)之泛型知識(shí)點(diǎn)總結(jié),文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java基礎(chǔ)的小伙伴們有很好的幫助,需要的朋友可以參考下2021-04-04
SpringBoot模擬員工數(shù)據(jù)庫(kù)并實(shí)現(xiàn)增刪改查操作
這篇文章主要給大家介紹了關(guān)于SpringBoot模擬員工數(shù)據(jù)庫(kù)并實(shí)現(xiàn)增刪改查操作的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2021-09-09
java中接口和事件監(jiān)聽(tīng)器的深入理解
這篇文章主要給大家介紹了關(guān)于java中接口和事件監(jiān)聽(tīng)器的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
IDEA中application.properties的圖標(biāo)顯示不正常的問(wèn)題及解決方法
這篇文章主要介紹了IDEA中application.properties的圖標(biāo)顯示不正常的問(wèn)題及解決方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
Springboot項(xiàng)目的服務(wù)器部署與發(fā)布方式
本文記錄了將Springboot項(xiàng)目部署到服務(wù)器并發(fā)布的過(guò)程,包括在IDEA中打包、選擇服務(wù)器、連接服務(wù)器、安裝環(huán)境、上傳jar包、配置環(huán)境變量以及運(yùn)行項(xiàng)目等步驟2025-03-03

