HttpURLConnection:无法检索正确的错误消息

HttpURLConnection : Unable to retrieve the correct error message

我正在使用 java HttpURLConnection 对象调用 REST 服务。

当 HTTP 服务器 returns 出现任何业务错误时,我无法正确检索错误。

例如,当我通过 SoapUI 调用 REST 服务时,出现以下错误

<exception>
    <errors>
    <error>
    <diagnostic>Matching item with shortCode = 1089992001234 found</diagnostic>
    <field>shortCode</field>
    <message>The Shortcode/CSG combination must be unique.</message>
    <objectFailingValidationClass>com.axiossystems.assyst.dto.organisationConfiguration.SectionDto</objectFailingValidationClass>
    <rule>isUniqueShortCodeWithCSG</rule>
    </error>
    </errors>
    <message>A complex validation error has been detected by the application.</message>
    <type>ComplexValidationException</type>
    </exception>

但是在java代码中出现以下错误,请求消息格式是正确的

java.io.IOException: Server returned HTTP response code: 400 for URL: https://it-test.ihc.eu/assystREST/v2/sections
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at sun.net.www.protocol.http.HttpURLConnection.run(HttpURLConnection.java:1676)
        at sun.net.www.protocol.http.HttpURLConnection.run(HttpURLConnection.java:1674)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1672)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
        at RestCaller.execute(RestCaller.java:59)
        at RestCaller.main(RestCaller.java:18)

谁能告诉我如何捕获从服务器返回的业务错误?就像在 SoapUI

中收到的一样

下面是我的代码

try
    {
    url = new URL(targetURL);
    connection = (HttpURLConnection) url.openConnection();

    connection.setRequestProperty("accept", "application/xml");
    String userpassword = username + ":" + password;
    String authStringEnc = new String(Base64.encodeBase64(userpassword.getBytes()));

    connection.setRequestProperty("Authorization", "Basic "+authStringEnc);
    if (HttpMethod == "POST") 
    {
    connection.setRequestMethod("POST");
    //connection.setRequestProperty("Content-Length","" + Integer.toString(urlParameters.getBytes().length));
    connection.setRequestProperty("Content-Type", "application/xml");
    connection.setRequestProperty("Content-Language", "en-US");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    OutputStream os = connection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(payLoad);
    writer.flush();
    writer.close();
    os.close();
    }
    int statusCode = connection.getResponseCode();


    System.out.println("--------000----------" + statusCode);           

    InputStream is = connection.getInputStream();
    System.out.println("--------111----------");            
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    System.out.println("--------222----------");            
    String line;
    System.out.println("--------333----------");            
    StringBuffer response = new StringBuffer();
    System.out.println("--------444----------");            

    while ((line = rd.readLine()) != null) 
    {
    response.append(line);
    response.append('\r');
    }

    rd.close();
    return response.toString();
    }
    catch (Exception e) 
    {
    System.out.println("--------exception----------");          
    e.printStackTrace();
    return "";
    }

400 错误表示您的响应数据格式错误,表示格式不正确。请再次检查您的回复 api。

如果出现错误(即 httpStatusCode 不是 200),您可能需要阅读 HttpUrlConnection 的 errorStream,如下所示。阅读 errorMessage 后,您可以将其反序列化为与您粘贴的 xml 输出相匹配的 DTO。请注意下面的 readErrorString() 是不完整的,希望您使用它仅供参考

if (statusCode != 200) {
  InputStream errorStream = connection.getErrorStream();
  String errorMessage = (errorStream != null) ? readErrorString(errorStream) : connection
                .getResponseMessage();
}
private void readErrorString(InputStream is) {
  String responseString = null;
  BufferedInputStream bis = null;
  try {
    StringBuilder sb = new StringBuilder();
    bis = new BufferedInputStream(inputStream);
    byte[] byteContents = new byte[4096];
    int bytesRead;
    String strContents;
    while ((bytesRead = bis.read(byteContents)) != -1) {
        strContents = new String(byteContents, 0, bytesRead, "UTF-8"); // You might need to replace the charSet as per the responseEncoding returned by httpurlconnection above
            sb.append(strContents);
    }
    responseString = sb.toString();
} finally {
    if (bis != null) {
        bis.close();
        }
    }
}

return responseString;