簡體   English   中英

獲取 java.io.IOException:服務器返回 HTTP 響應代碼:URL 的 400:使用返回 400 狀態代碼的 url 時

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

我正在嘗試使用以下代碼使用Groovy執行獲取請求:

字符串 url = “端點的 url” def responseXml = new 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>

在這種情況下,解析方法拋出:


    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?

在問題中,因為我們正在獲取 GET 請求的 400 狀態代碼。 所以內置的 XmlSlurper().parse(URI) 方法不起作用,因為它拋出 io.Exception。 Groovy 還支持 HTTP 方法用於 api 請求和響應,以下對我有用:

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())
}

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)
}

更好的方法是使用實際的全功能 HTTP 客戶端,例如 Spring Framework 的HttpClientRestTemplate類。

您應該檢查返回碼,然后從 http 請求實例中獲取錯誤 stream 以防出錯。 問題本身與 JsonSlurper 無關,因為如果服務未成功返回返回碼(400、401、500 等),則 http 請求實例不會返回“輸入流”實例。POST 示例如下所示:

http= new URL("yourUrl").openConnection() as HttpURLConnection
http.setRequestMethod('POST')
http.setDoOutput(true)
http.setRequestProperty("Content-Type", 'application/json')
http.setRequestProperty("Accept", 'application/json')
http.setRequestProperty("Authorization", "Bearer $yourTokenVariable")
http.outputStream.write(data.getBytes("UTF-8"))
http.connect()
 
if(http.getResponseCode() != 200 && http.getResponseCode() != 201){ 
     throw new InvalidInputException("There was an error: " + http.getErrorStream().getText("UTF-8"))
} else {
    //You can take input stream here
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM