调用SOAP Web服务

我有一个要调用的SOAP Web服务,以下是我的代码:

private List<Guaranty> getGuarantyList(String nationalId, String centerBankCode) throws IOException{
        
        try {
            fixHttpsHandler();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

        // Code to make a webservice HTTP request
        String responseString = "";
        String outputString = "";
        String wsEndPoint = "http://192.168.5.202/services/out.asmx";
        URL url = new URL(wsEndPoint);
        URLConnection connection = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) connection;
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        String xmlInput = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:pos=\"http://postbank.ir/\">\r\n" + 
                "   <soapenv:Header>\r\n" + 
                "      <pos:PostbankAuth>\r\n" + 
                "         <!--Optional:-->\r\n" + 
                "         <pos:UserName>ebank</pos:UserName>\r\n" + 
                "         <!--Optional:-->\r\n" + 
                "         <pos:Password>qwer@123</pos:Password>\r\n" + 
                "      </pos:PostbankAuth>\r\n" + 
                "   </soapenv:Header>\r\n" + 
                "   <soapenv:Body>\r\n" + 
                "      <pos:getGuaranty>\r\n" + 
                "         <!--Optional:-->\r\n" + 
                "         <pos:nationalCode>" + nationalId + "</pos:nationalCode>\r\n" + 
                "         <!--Optional:-->\r\n" + 
                "         <pos:centerBankCode>" + centerBankCode + "</pos:centerBankCode>\r\n" + 
                "         <!--Optional:-->\r\n" + 
                "         <pos:length>10</pos:length>\r\n" + 
                "         <pos:offset>0</pos:offset>\r\n" + 
                "      </pos:getGuaranty>\r\n" + 
                "   </soapenv:Body>\r\n" + 
                "</soapenv:Envelope>";
        byte[] buffer = new byte[xmlInput.length()];
        buffer = xmlInput.getBytes();
        bout.write(buffer);
        byte[] b = bout.toByteArray();
        String SOAPAction = "http://postbank.ir/getGuaranty";
        httpConn.setRequestProperty("Accept-Encoding", "gzip,deflate");
        httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        httpConn.setRequestProperty("SOAPAction", SOAPAction);
        httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
        httpConn.setRequestProperty("Host", "192.168.5.202");
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        httpConn.setRequestProperty("User-Agent", "Apache-HttpClient/4.5.5 (Java/16.0.1)");
        httpConn.setRequestMethod("POST");
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        OutputStream out = httpConn.getOutputStream();
        // Write the content of the request to the outputstream of the HTTP
        // Connection.
        out.write(b);
        out.close();
        // Ready with sending the request.
        // Read the response.

        InputStreamReader isr = new InputStreamReader(httpConn.getInputStream(), Charset.forName("UTF-8"));

        BufferedReader in = new BufferedReader(isr);
        // Write the SOAP message response to a String.
        while ((responseString = in.readLine()) != null) {
            outputString = outputString + responseString;
        }
            
        String formattedSOAPResponse = formatXML(outputString);
        return formattedSOAPResponse ;
        
    }

但我得到的是响应,而不是一个可读的XML:

_____I�%&/m�{_J�J��t�_�$ؐ@������_iG#)�*��eVe]f@�흼��{���{���;�N'���?\fd_l��J�ɞ!���?~|?"�_�_ez��MQ-?�hw��Q�/�լX^|�Ѻ=�>���8z�T�����2/�U��+��>��yۮ_ݽ�L��"k��&gt;W��]�r7ח�~���k�������_7���ٽ�{��5_�.�M�-��{kv�[)�O����㋼�|��ٲ�~�7�j�(�_Ъj�I�|;.��n�ºl�__�7Mv�_Uo_�5�?~��N�|v�����]���Y�__��$ϖG��E�^��ۏ�>�1������I~Q,�e��GG{;{{�;����ٻ�hg����νG��-ۚ^����j潹��Km�_�ыl�5����_�����f�_�=6_5 k C wv?°wp n RØ__nz 6|V†]7 g NO_\51 ku_5äi E^c(§7_X o_O_?&amp;_o?o_F_[_W[տ�7_�����_�_��dzu��$�C_����q��aB��2}�{���ӶG�_�TD���������;?�y0�9,�B$o�oW�,��g���Ͻ�o�5����c������~���3�q��٫��;{�4=43�v�_�?x���s_�:�_B���_�7 �;4�;;�_t^Ֆ�� �{��������h�פ����o�1D����#R"�_�o��4"��_A��_t��;+��������?}@�_�uM__o�2_ͫe��r v_����}�C�^c_BL�^z�������S~��9z�^��y3��__�5���)+?8_o K?_mään_Q_o 5_w N?G.q"i_‘}iW§_°ZH

这种方式适用于其他Web服务,但不适用于此Web服务.我在SOAP-UI中测试了Web服务,它工作正常…… 谢谢

推荐答案

您收到的乱码响应表示该响应是用gZip或Eflate编码压缩的.为了正确处理这个压缩的响应,您需要在将其作为可读的XML读取之前对其进行解码.

import java.io.*;
import java.net.*;

import java.util.zip.GZIPInputStream;

private List<Guaranty> getGuarantyList(String nationalId, String centerBankCode) throws IOException {
    try {
        fixHttpsHandler();
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }

    String responseString = "";
    String outputString = "";
    String wsEndPoint = "http://192.168.5.202/services/out.asmx";
    URL url = new URL(wsEndPoint);
    URLConnection connection = url.openConnection();
    HttpURLConnection httpConn = (HttpURLConnection) connection;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    String xmlInput = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:pos=\"http://postbank.ir/\">\r\n" + 
            ...
            "</soapenv:Envelope>";
    byte[] buffer = new byte[xmlInput.length()];
    buffer = xmlInput.getBytes();
    bout.write(buffer);
    byte[] b = bout.toByteArray();
    String SOAPAction = "http://postbank.ir/getGuaranty";
    httpConn.setRequestProperty("Accept-Encoding", "gzip,deflate");
    httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
    httpConn.setRequestProperty("SOAPAction", SOAPAction);
    httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
    httpConn.setRequestProperty("Host", "192.168.5.202");
    httpConn.setRequestProperty("Connection", "Keep-Alive");
    httpConn.setRequestProperty("User-Agent", "Apache-HttpClient/4.5.5 (Java/16.0.1)");
    httpConn.setRequestMethod("POST");
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    OutputStream out = httpConn.getOutputStream();
    out.write(b);
    out.close();

    InputStream inputStream = httpConn.getInputStream();
    String contentEncoding = httpConn.getContentEncoding();

    if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
        inputStream = new GZIPInputStream(inputStream);
    } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
        inputStream = new InflaterInputStream(inputStream);
    }

    InputStreamReader isr = new InputStreamReader(inputStream, Charset.forName("UTF-8"));

    BufferedReader in = new BufferedReader(isr);
    while ((responseString = in.readLine()) != null) {
        outputString = outputString + responseString;
    }

    String formattedSOAPResponse = formatXML(outputString);
    return formattedSOAPResponse;
}

我添加了判断HTTP响应的Content-Ending头的逻辑.如果指示为GZIP压缩,则将inputStream包装在GZIPInputStream中进行解压缩.类似地,如果编码是DEFATE,则它被包装在InflaterInputStream中.

Java相关问答推荐

try 使用Java 9或更高版本对特殊对象图进行解析时出现NullPointerException

在Java Swing Paint应用程序中捕获快速鼠标移动时遇到困难

我无法获取我的Java Spring应用程序的Logback跟踪日志(log)输出

用户填充的数组列表永不结束循环

如何让JVM在SIGSEGV崩溃后快速退出?

使用多个RemoteDatabase对象的一个线程

%This内置函数示例

try 在Android Studio中的infoWindow中使用EditText(Java)

在处理2个映射表时,没有更多的数据可从套接字读取

Java中不兼容的泛型类型

一对多关系和ID生成

将stringBuilder + forloop转换为stream + map

通过Java列表中的某些字段搜索值

使用SWIG将C++自定义单元类型转换为基本Java类型

深度优先搜索实现:算法只向右搜索

如何对存储为字符串的大数字数组进行排序?

Java类型推断:为什么要编译它?

控制器建议异常处理

这是JavaFX SceneBuilder的错误吗?

如何在Java上为循环数组从synchronized迁移到ReentrantLock