如何在出错时接收从http连接返回的原始数据

时间:2014-05-13 17:50:53

标签: java http rest httpurlconnection

最重要的是,我想获得exceptionMessage,当我使用SoapUI发出请求时,我可以将其视为返回数据的一部分。我在HttpURLConnection中看不到任何包含此详细信息的内容。只有responseCode和responseMessage,这很好,但缺乏我正在寻找的描述。

此外,SoapUI是否将这些原始数据解析为JSON和XML本身,或者是否有一种简单的方法可以通过Java将其作为JSON获取?

由于

1 个答案:

答案 0 :(得分:1)

服务器返回HTTP标头,在大多数情况下是一个正文。为了在出现错误时获取正文,您必须执行以下操作:

InputStream is;    
if (conn.getResponseCode() / 100 == 2) { // HTTP status code 2xx, e.g. 200
    is = conn.getInputStream();

    // read input stream -> this is the content you wanted

} else {
    is = conn.getErrorStream();

    // read input stream -> contains a description of the error
    // depending on header "Content-Type" you can also parse the stream
    // as JSON or XML or HTML ...

}