获取 java.io.IOException:服务器 returned HTTP 响应代码:URL 的 400:当使用 url 时 return 400 状态代码

Getting java.io.IOException: Server returned HTTP response code: 400 for URL: when using a url which return 400 status code

我正在尝试使用以下代码使用 Groovy 执行获取请求:

String url = "端点的url" def responseXml = new XmlSlurper().parse(url)

如果端点 returns 状态为 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>

在这种情况下解析方法抛出:


    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?

HttpURLConnection class 获取响应文本而不是通过 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)
}

更好的方法是使用实​​际的 full-featured HTTP 客户端,例如 Spring 框架的 HttpClientRestTemplate classes.

在问题中,因为我们正在获取 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())
}