如何在使用Java调用SOAP Web服务时修复无法读取的XML响应?

huangapple go评论59阅读模式
英文:

How to fix unreadable XML response when calling a SOAP web service with Java?

问题

I have translated the code part for you:

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;

}

If you need further assistance or have any questions, please let me know.

英文:

calling soap web service

I have a soap web service to call, here is my code:

private List&lt;Guaranty&gt; 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 = &quot;&quot;;
String outputString = &quot;&quot;;
String wsEndPoint = &quot;http://192.168.5.202/services/out.asmx&quot;;
URL url = new URL(wsEndPoint);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String xmlInput = &quot;&lt;soapenv:Envelope xmlns:soapenv=\&quot;http://schemas.xmlsoap.org/soap/envelope/\&quot; xmlns:pos=\&quot;http://postbank.ir/\&quot;&gt;\r\n&quot; + 
&quot;   &lt;soapenv:Header&gt;\r\n&quot; + 
&quot;      &lt;pos:PostbankAuth&gt;\r\n&quot; + 
&quot;         &lt;!--Optional:--&gt;\r\n&quot; + 
&quot;         &lt;pos:UserName&gt;ebank&lt;/pos:UserName&gt;\r\n&quot; + 
&quot;         &lt;!--Optional:--&gt;\r\n&quot; + 
&quot;         &lt;pos:Password&gt;qwer@123&lt;/pos:Password&gt;\r\n&quot; + 
&quot;      &lt;/pos:PostbankAuth&gt;\r\n&quot; + 
&quot;   &lt;/soapenv:Header&gt;\r\n&quot; + 
&quot;   &lt;soapenv:Body&gt;\r\n&quot; + 
&quot;      &lt;pos:getGuaranty&gt;\r\n&quot; + 
&quot;         &lt;!--Optional:--&gt;\r\n&quot; + 
&quot;         &lt;pos:nationalCode&gt;&quot; + nationalId + &quot;&lt;/pos:nationalCode&gt;\r\n&quot; + 
&quot;         &lt;!--Optional:--&gt;\r\n&quot; + 
&quot;         &lt;pos:centerBankCode&gt;&quot; + centerBankCode + &quot;&lt;/pos:centerBankCode&gt;\r\n&quot; + 
&quot;         &lt;!--Optional:--&gt;\r\n&quot; + 
&quot;         &lt;pos:length&gt;10&lt;/pos:length&gt;\r\n&quot; + 
&quot;         &lt;pos:offset&gt;0&lt;/pos:offset&gt;\r\n&quot; + 
&quot;      &lt;/pos:getGuaranty&gt;\r\n&quot; + 
&quot;   &lt;/soapenv:Body&gt;\r\n&quot; + 
&quot;&lt;/soapenv:Envelope&gt;&quot;;
byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = &quot;http://postbank.ir/getGuaranty&quot;;
httpConn.setRequestProperty(&quot;Accept-Encoding&quot;, &quot;gzip,deflate&quot;);
httpConn.setRequestProperty(&quot;Content-Type&quot;, &quot;text/xml; charset=utf-8&quot;);
httpConn.setRequestProperty(&quot;SOAPAction&quot;, SOAPAction);
httpConn.setRequestProperty(&quot;Content-Length&quot;, String.valueOf(b.length));
httpConn.setRequestProperty(&quot;Host&quot;, &quot;192.168.5.202&quot;);
httpConn.setRequestProperty(&quot;Connection&quot;, &quot;Keep-Alive&quot;);
httpConn.setRequestProperty(&quot;User-Agent&quot;, &quot;Apache-HttpClient/4.5.5 (Java/16.0.1)&quot;);
httpConn.setRequestMethod(&quot;POST&quot;);
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(&quot;UTF-8&quot;));
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 ;
}

but i get this as response instead a readable xml:

�________�__I�%&amp;/m�{_J�J��t�_�$ؐ@������_iG#)�*��eVe]f@�흼��{���{���;�N'���?\fd_l��J�ɞ!���?~|?"�_�_ez��MQ-?�hw��Q�/�լX^|�Ѻ=�>���8z�T�����2/�U��+��>��yۮ_ݽ�L��"k��>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��_��?&����_�_����_�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

this way works for other web services but not this one. i tested the web service in soap-ui and it works correctly...
thanks

答案1

得分: 4

The provided Java code snippet handles decoding of compressed HTTP responses. If the Content-Encoding header indicates gzip compression, the response is decompressed using GZIPInputStream. If the encoding is deflate, it is decompressed using InflaterInputStream.

英文:

The garbled response you're receiving indicates that the response is compressed with gzip or deflate encoding. To properly handle this compressed response, you need to decode it before reading it as a readable XML.

import java.io.*;
import java.net.*;
import java.util.zip.GZIPInputStream;
private List&lt;Guaranty&gt; getGuarantyList(String nationalId, String centerBankCode) throws IOException {
try {
fixHttpsHandler();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
String responseString = &quot;&quot;;
String outputString = &quot;&quot;;
String wsEndPoint = &quot;http://192.168.5.202/services/out.asmx&quot;;
URL url = new URL(wsEndPoint);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String xmlInput = &quot;&lt;soapenv:Envelope xmlns:soapenv=\&quot;http://schemas.xmlsoap.org/soap/envelope/\&quot; xmlns:pos=\&quot;http://postbank.ir/\&quot;&gt;\r\n&quot; + 
...
&quot;&lt;/soapenv:Envelope&gt;&quot;;
byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = &quot;http://postbank.ir/getGuaranty&quot;;
httpConn.setRequestProperty(&quot;Accept-Encoding&quot;, &quot;gzip,deflate&quot;);
httpConn.setRequestProperty(&quot;Content-Type&quot;, &quot;text/xml; charset=utf-8&quot;);
httpConn.setRequestProperty(&quot;SOAPAction&quot;, SOAPAction);
httpConn.setRequestProperty(&quot;Content-Length&quot;, String.valueOf(b.length));
httpConn.setRequestProperty(&quot;Host&quot;, &quot;192.168.5.202&quot;);
httpConn.setRequestProperty(&quot;Connection&quot;, &quot;Keep-Alive&quot;);
httpConn.setRequestProperty(&quot;User-Agent&quot;, &quot;Apache-HttpClient/4.5.5 (Java/16.0.1)&quot;);
httpConn.setRequestMethod(&quot;POST&quot;);
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 &amp;&amp; contentEncoding.equalsIgnoreCase(&quot;gzip&quot;)) {
inputStream = new GZIPInputStream(inputStream);
} else if (contentEncoding != null &amp;&amp; contentEncoding.equalsIgnoreCase(&quot;deflate&quot;)) {
inputStream = new InflaterInputStream(inputStream);
}
InputStreamReader isr = new InputStreamReader(inputStream, Charset.forName(&quot;UTF-8&quot;));
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
String formattedSOAPResponse = formatXML(outputString);
return formattedSOAPResponse;
}

I added logic to check the Content-Encoding header of the HTTP response. If it indicates gzip compression, the inputStream is wrapped in a GZIPInputStream for decompression. Similarly, if the encoding is deflate, it is wrapped in an InflaterInputStream.

huangapple
  • 本文由 发表于 2023年5月21日 14:39:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298608.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定