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

时间:2016-05-26 10:50:50

标签: java ioexception http-status-code-400

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

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

例如,当我通过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$6.run(HttpURLConnection.java:1676)
        at sun.net.www.protocol.http.HttpURLConnection$6.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 "";
    }

2 个答案:

答案 0 :(得分:0)

如果出现错误(即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;

答案 1 :(得分:-1)

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