java - How do I read HTTP status code from RestTemplate? -
i call rest api using resttemplate. response don't has issues.i need http status code this.
request ok- 200
unauthorized - 400
according many post met bellow answer.
resttemplate template = new resttemplate(); httpentity<string> response = template.exchange(url, httpmethod.post, request, string.class); string resultstring = response.getbody(); httpheaders headers = response.getheaders();
in here used exchange method response.(template.exchange....) used
postforobject method
this code
public balancecheckresponse accounttotal(string counteralias, string counterauth, string subscribertype, string subscribervalue, string accessmode, string token) { balancecheckresponse objresponse = new balancecheckresponse(); try { balancecheckrequest objrequest = new balancecheckrequest(); objrequest.setcounteralias(counteralias); objrequest.setcounterauth(counterauth); objrequest.setsubscribertype(subscribertype); objrequest.setsubscribervalue(subscribervalue); objrequest.setaccessmode(accessmode); resttemplate rsttemp = new resttemplate(); final string url = "https://ideabiz.lk/apicall/startpoint/v1/balancecheck"; list<httpmessageconverter<?>> messageconverters = new arraylist<httpmessageconverter<?>>(); mappingjackson2httpmessageconverter map =new mappingjackson2httpmessageconverter(); messageconverters.add(map); //messageconverters.add(new stringhttpmessageconverter()); rsttemp.setmessageconverters(messageconverters); httpheaders headers = new httpheaders(); headers.setcontenttype(mediatype.application_json); headers.add("authorization", "bearer "+token); httpentity<balancecheckrequest> entity = new httpentity<balancecheckrequest>(objrequest,headers); objresponse = rsttemp.postforobject(url,entity, balancecheckresponse.class ); } catch (exception e) { e.printstacktrace(); } system.out.println(objresponse.getcurrentbalance()); return objresponse; }
in code
objresponse.getheaders();
show error. can in here. have idea?
by default, resttemplate
uses defaultresponseerrorhandler
, throws exception if not receive 1 of responses considered successful. means in event of error, e.printstacktrace();
statement print stack trace. (which go unnoticed.)
if that's not enough you, there number of ways circumvent behavior, 1 of them supplying own error handler using seterrorhandler( responseerrorhandler errorhandler )
.
Comments
Post a Comment