2017-05-22 58 views
0

我使用具有低于头Spring框架:获取状态响应(如400,500)

import org.springframework.web.client.RestTemplate; 

我想获取的状态代码来写我的记录器。我如何获得restTemplate的响应?

public boolean performTransition(String transitionId,String jiraId){ 

    JiraID id = new JiraID(transitionId); 
    JiraTransition transition = new JiraTransition(); 
    transition.setTransition(id); 

    String transitionUrlFormat = String.format(transitionUrl,jiraId); 

    RestTemplate template = new RestTemplate(); 

    HttpEntity epicEntityRequest = new HttpEntity(transition,createHttpHeaders()); 

    HttpEntity<String> epicEntityResponse= template.exchange(transitionUrlFormat , HttpMethod.POST, epicEntityRequest, String.class); 
    //TODO: verify code 204 
    ResponseEntity<String> responseEntity= (ResponseEntity<String>) epicEntityResponse; 
    epicEntityResponse.getBody(); 
    //System.out.println("LOG" +responseEntity); 
    //responseEntity.getStatusCode(); 
    HttpStatus statusCode = responseEntity.getStatusCode(); 


    return true; 
} 

此外,我想检查400以上的响应代码我想写log.warning()。

+1

显示您的代码片段 – pvpkiran

+0

编辑答案。 –

回答

0

问题需要更详细的阐述。你的意思是这样的:

ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class); 
int statusCode = response.getStatusCode().value(); 

这给了状态代码为int,你可以这样做:

if(statusCode > 400){ 
//Log here 
} 

ResponseEntity可以给你一个完整的HTTP响应状态代码,身体和头。

Ofcourse,你需要初始化restTemplate,或者使用默认值:

RestTemplate restTemplate = new RestTemplate(); 

这使用,默认:SimpleClientHttpRequestFactory,或者如果你想要更多的东西来配置你可以使用:HttpComponentsClientHttpRequestFactory其中有许多CONFIGS,像连接池读取超时,连接超时等。

+0

如果条件引发此错误ERR:操作符'>'不能应用于'org.springframework.http.HttpStatus','int' 我得到这个错误,我不能将它声明为int,所以我改变了变量键入HttpStatus – DeathPulse

+0

您可以从statusCode.value()获取int值; –

+0

@DeathPulse - 有用吗? –