我正在尝试使用Groovy执行get请求,代码如下:
字符串url =“端点的url”def responseXml =新的XmlSlurper().parse(url)
如果端点返回的状态为200,则一切正常,但有一种情况下,我们必须验证如下所示的错误响应,返回的状态为400:
<errors>
<error>One of the following parameters is required: xyz, abc.</error>
<error>One of the following parameters is required: xyz, mno.</error>
</errors>
在本例中,parse方法抛出:
java.io.IOException: Server returned HTTP response code: 400 for URL: "actual endpoint throwing error"
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1900)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1498)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:646)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(XMLVersionDetector.java:150)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:831)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:796)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:142)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1216)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:644)
at groovy.util.XmlSlurper.parse(XmlSlurper.java:205)
at groovy.util.XmlSlurper.parse(XmlSlurper.java:271)
Can anyone pls suggest how to handle if server give error message by throwing 400 status code?
2条答案
按热度按时间kd3sttzy1#
在这个问题中,因为我们得到了GET请求的400状态代码。所以内置的XmlSlurper().parse(URI)方法不起作用,因为它抛出io.Exception。Groovy还支持API请求和响应的HTTP方法,下面的方法对我很有效:
vcudknz32#
从
HttpURLConnection
类而不是通过XmlSlurper
隐式地获取响应文本,可以让您在处理不成功的响应时有更大的灵活性。更好的方法是使用一个实际的全功能HTTP客户机,比如Spring框架的
HttpClient
或RestTemplate
类。