groovy 正在获取java.io. IO异常:服务器返回HTTP响应代码:400用于URL:当使用返回400状态代码的URL时

wydwbb8l  于 2022-11-01  发布在  Java
关注(0)|答案(2)|浏览(278)

我正在尝试使用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?
kd3sttzy

kd3sttzy1#

在这个问题中,因为我们得到了GET请求的400状态代码。所以内置的XmlSlurper().parse(URI)方法不起作用,因为它抛出io.Exception。Groovy还支持API请求和响应的HTTP方法,下面的方法对我很有效:

def getReponseBody(endpoint) {     
    URL url = new URL(endpoint)
    HttpURLConnection get = (HttpURLConnection)url.openConnection()
    get.setRequestMethod("GET")
    def getRC = get.getResponseCode()

    BufferedReader br = new BufferedReader(new InputStreamReader(get.getErrorStream()))
    StringBuffer xmlObject = new StringBuffer()
    def eachLine
    while((eachLine = br.readLine()) !=null){
        xmlObject.append(eachLine)
    }
    get.disconnect()
    return new XmlSlurper().parseText(xmlObject.toString())
}
vcudknz3

vcudknz32#

HttpURLConnection类而不是通过XmlSlurper隐式地获取响应文本,可以让您在处理不成功的响应时有更大的灵活性。

def connection = new URL('https://your.url/goes.here').openConnection()
def content = { ->
    try {
        connection.content as String
    } catch (e) {
        connection.responseMessage
    }
}()

if (content) {
    def responseXml = new XmlSlurper().parseText(content)
    doStuffWithResponseXml(responseXml)
}

更好的方法是使用一个实际的全功能HTTP客户机,比如Spring框架的HttpClientRestTemplate类。

相关问题