java记录来自服务器的xml响应

时间:2018-08-16 07:29:27

标签: java xml

HTTP/1.1 500 Internal Server Error
Content-Type: application/xml; charset=UTF-8
Connection: close
Content-Length: 401

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<fulfillmentService><responseCode>1106</responseCode> 
<status>FAILURE</status><systemType>CIS</systemType> 
<responseDescription>Sorry! We are unable to process your request. Call 111 for customer care or visit www.mtnzambia.com.</responseDescription><requestId>WEB_10.100.244.97_92505288-f094-4834-a978-658c19e3f656</requestId></fulfillmentService>

我需要一种在Java中记录此XML响应的方法。当我从Java发送请求时,将返回此内容。我需要一种打印响应描述的方法。

下面是我的Java代码:

 url = new URL(endpoint);


        connection = (HttpURLConnection) url.openConnection();
  responseCode = connection.getResponseCode();
        respTxt = connection.getResponseMessage();
        System.out.println("Status code after sending the the payload to mtn => " + responseCode + " Now waiting for response: ");
        Object vm = connection.toString();
        //   BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        PrintWriter pw = new PrintWriter(connection.getOutputStream());

        // send xml to jsp
        // pw.write(buffer, 0, bytes_read);
        // pw.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
        }

1 个答案:

答案 0 :(得分:2)

如果响应代码不是200或2xx或3xx,请使用getErrorStream()而不是getInputStream()。

请参阅How to get response body using HttpURLConnection, when code other than 2xx is returned?

    url = new URL(endpoint);

            connection = (HttpURLConnection) url.openConnection();
            responseCode = connection.getResponseCode();
            respTxt = connection.getResponseMessage();
            System.out.println("Status code after sending the the payload to mtn => " + responseCode + " Now waiting for response: ");
            Object vm = connection.toString();
            //   BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            //PrintWriter pw = new PrintWriter(connection.getOutputStream());

            // send xml to jsp
            // pw.write(buffer, 0, bytes_read);
            // pw.close();
            BufferedReader in;

            if(responseCode >= 200 && responseCode  < 400) {
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            } else {
                in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            }
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
相关问题