Web Service之Soap请求响应内容中文编码解密

java模拟Soap请求测试Web Service接口,发现Web Service响应内容中的中文竟然是编码格式。比如:

中文:退保成功

Soap中文编码:退保成功

我仔细分析后发现,退编码实际上就是Unicode编码的Soap版,正规的Unicode编码是\u9000,Soap改成自己的格式&#x[4位内容];格式。

还有其他的比如:

换行,Soap编码:

单引号,Soap为转换为html编码:'

与号,Soap为转换为html编码:&

小于号,Soap为转换为html编码:<

等等

因此,结合以上情况。想看到直观的内容,就需要解密这些编码了。解密简单,利用正则替换实现。这里介绍下Soap中文编码的解密:

1.将退替换成\u9000。替换&#x为\u,去掉分号

2.解密Unicode编码\u9000

为了更直观看Soap响应内容,我还替换了Soap换行符编码

&#xd替换为\n换行符

java代码:

WSClient_SOAP.java

package com.sfasdfsdafd.core.webservice.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.junit.Test;

import com.sfasdfsdafd.core.utils.xml.XmlUtil4Jdom;

/**
 * 类名:com.sfasdfsdafd.core.webservice.WSClient_SOAP
 *
 * <pre>
 * 描述: 测试类
 *     基本思路:
 *     public方法:
 *     特别说明:
 * 创建时间:2013-4-9 下午10:29:04
 * 修改说明: 类的修改说明
 * </pre>
 */
public class WSClient_SOAP {

    static Logger log = Logger.getLogger(WSClient_SOAP.class);// 日志记录对象

    private static String NAMESPACE = "http://access.control.core.sfasdfsdafd.com/";
    private static String NAMESPACE_JBOSS = "http://access.restful.core.sfasdfsdafd.com/";
    private static String ENCODING_UTF_8 = "UTF-8";
    private static String ENCODING_GBK = "GBK";

    /**
     * 测试WebService接口 <br><pre>
     * @param 参数类型 参数名 说明
     * @return void 说明
     * @throws 异常类型 说明
     */
//    @Test
    public void testSOAPRequest() throws IOException,Exception {
        long d1 = System.currentTimeMillis();
        String returnMsg = "";
        StringBuffer sTotalString = new StringBuffer();
        OutputStream os = null;
        URLConnection conn = null;
        InputStream is = null;
        try {
            String iDzswXml = "模拟客户端请求WebService接口";

            File file = new File("abc.xml");
            iDzswXml = FileUtils.readFileToString(file, ENCODING_GBK);
            iDzswXml = encodeValue(iDzswXml);

            StringBuffer soap = new StringBuffer();
                soap.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"")
                    .append(" xmlns:acc=\"" + NAMESPACE + "\"> ")
                    .append(" <soapenv:Header/>")
                    .append(" <soapenv:Body>")
                    .append(" <execService4DZSW>")
                    .append(" <iDzswXML>")
                    .append(iDzswXml)
                    .append(" </iDzswXML>")
                    .append(" </execService4DZSW>")
                    .append("</soapenv:Body>")
                    .append(" </soapenv:Envelope>");

            URL url = new URL("http://localhost:8080/iDzsw-interface/ws/iDzswAICWS");
//            URL url = new URL("http://10.111.184.20:13000/iDzsw-interface/ws/iDzswAICWS");
            conn = url.openConnection();
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestProperty("Content-Length", Integer.toString(soap.length()));
            conn.setRequestProperty("Content-Type", "text/xml; charset=" + ENCODING_GBK);
            conn.setRequestProperty("SOAPAction", "execService4DZSW");

            os = conn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, ENCODING_GBK);

            String reqs = soap.toString();
            reqs = decodeValue(reqs);
            log.info("模拟客户端请求WebService发送报文:\n" + reqs);

            osw.write(soap.toString());
            osw.flush();
            osw.close();

            String sCurrentLine = "";
            is = conn.getInputStream();
            BufferedReader l_reader = new BufferedReader(new InputStreamReader(is, ENCODING_GBK));
            while ((sCurrentLine = l_reader.readLine()) != null) {
                sTotalString.append(sCurrentLine);
            }
            returnMsg = sTotalString.toString();
            returnMsg = decodeValue(returnMsg);
            returnMsg = decode4SoapValue(returnMsg);
        } catch (Exception e) {
            log.error("请求WebService出现异常", e);
        } finally {
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        }

        long d2 = System.currentTimeMillis();
        log.info("WebService返回:\t" + returnMsg + "\n耗时:"+ (d2 - d1));
    }

//    @Test
    public void testSOAPRequest4JBoss() throws IOException,Exception {
        long d1 = System.currentTimeMillis();
        String returnMsg = "";
        StringBuffer sTotalString = new StringBuffer();
        OutputStream os = null;
        URLConnection conn = null;
        InputStream is = null;
        try {
            String iDzswXml = "模拟客户端请求WebService接口";

            File file = new File("abc.xml");
            iDzswXml = FileUtils.readFileToString(file, ENCODING_GBK);
            iDzswXml = encodeValue(iDzswXml);

            StringBuffer soap = new StringBuffer();
                soap.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"")
                    .append(" xmlns:acc=\"" + NAMESPACE_JBOSS + "\"> ")
                    .append(" <soapenv:Header/>")
                    .append(" <soapenv:Body>")
                    .append(" <acc:execService4DZSW>")
                    .append(" <iDzswXML>")
                    .append(iDzswXml)
                    .append(" </iDzswXML>")
                    .append(" </acc:execService4DZSW>")
                    .append("</soapenv:Body>")
                    .append(" </soapenv:Envelope>");

            URL url = new URL("http://localhost:8081/iDzsw-interface/ws/iDzswAICWS");
            conn = url.openConnection();
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestProperty("Content-Length", Integer.toString(soap.length()));
            conn.setRequestProperty("Content-Type", "text/xml; charset=" + ENCODING_GBK);
            conn.setRequestProperty("SOAPAction", "execService4DZSW");

            os = conn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, ENCODING_GBK);

            String reqs = soap.toString();
            reqs = decodeValue(reqs);
            log.info("模拟客户端请求WebService发送报文:\n" + reqs);

            osw.write(soap.toString());
            osw.flush();
            osw.close();

            String sCurrentLine = "";
            is = conn.getInputStream();
            BufferedReader l_reader = new BufferedReader(new InputStreamReader(is, ENCODING_GBK));
            while ((sCurrentLine = l_reader.readLine()) != null) {
                sTotalString.append(sCurrentLine);
            }
            returnMsg = sTotalString.toString();
            returnMsg = decodeValue(returnMsg);
            returnMsg = decode4SoapValue(returnMsg);
        } catch (Exception e) {
            log.error("请求WebService出现异常", e);
        } finally {
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        }

        long d2 = System.currentTimeMillis();
        log.info("WebService返回:\t" + returnMsg + "\n耗时:"+ (d2 - d1));
    }

    /**
     * 测试合zuojigou的回调接口 <br><pre>
     * @param 参数类型 参数名 说明
     * @return void 说明
     * @throws 异常类型 说明
     */
//    @Test
    public void testCallback() throws IOException,Exception {
        long d1 = System.currentTimeMillis();
        String returnMsg = "";
        StringBuffer sTotalString = new StringBuffer();
        OutputStream os = null;
        URLConnection conn = null;
        InputStream is = null;
        try {
            String iDzswXml = "URL TEST";
            File file = new File("abc.xml");
            iDzswXml = FileUtils.readFileToString(file, ENCODING_GBK);
            iDzswXml = encodeValue(iDzswXml);

            StringBuffer soap = new StringBuffer();
                soap.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"")
                    .append(" xmlns:acc=\"" + NAMESPACE + "\"> ")
                    .append(" <soapenv:Header/>")
                    .append(" <soapenv:Body>")
                    .append(" <callbackProcess>")
                    .append(" <xmlMsg>")
                    .append(iDzswXml)
                    .append(" </xmlMsg>")
                    .append(" </callbackProcess>")
                    .append("</soapenv:Body>")
                    .append(" </soapenv:Envelope>");

            URL url = new URL("http://localhost:8080/iDzsw-interface/ws/abCallbackWS");
            conn = url.openConnection();
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestProperty("Content-Length", Integer.toString(soap.length()));
            conn.setRequestProperty("Content-Type", "text/xml; charset=" + ENCODING_GBK);
            conn.setRequestProperty("SOAPAction", "execService4DZSW");

            os = conn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, ENCODING_GBK);

            log.info("模拟客户端请求WebService发送报文:\n" + soap.toString());

            osw.write(soap.toString());
            osw.flush();
            osw.close();

            String sCurrentLine = "";
            is = conn.getInputStream();
            BufferedReader l_reader = new BufferedReader(new InputStreamReader(is, ENCODING_GBK));
            while ((sCurrentLine = l_reader.readLine()) != null) {
                sTotalString.append(sCurrentLine);
            }
            returnMsg = sTotalString.toString();
        } catch (Exception e) {
            log.error("请求WebService出现异常", e);
        } finally {
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        }

        long d2 = System.currentTimeMillis();
        log.info("WebService返回:\t" + returnMsg + "\n耗时:"+ (d2 - d1));
    }

    /**
     * 测试Socket接口 <br><pre>
     * @param 参数类型 参数名 说明
     * @return void 说明
     * @throws 异常类型 说明
     */
    @Test
    public void testSocket() {
        // 本地地址
        String coreAddress = "127.0.0.1";
        // 测试环境地址
//        String coreAddress = "10.111.184.20";
        // 测试环境外网访问地址
//        String coreAddress = "221.166.48.163";
        // 新Project端口号
        int corePort = 8001;
        // 老Project端口号
//        int corePort = 8080;

        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;
        String message = null;
        // 收到的报文
        StringBuffer stringBuffer = new StringBuffer();
        String receiveString = null;

        File file = new File("abc.xml");

        try {
            socket = new Socket(coreAddress, corePort);
            out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), ENCODING_GBK), true);

            String msg = FileUtils.readFileToString(file, ENCODING_GBK);
            out.println(msg);
            out.flush();

            in = new BufferedReader(new InputStreamReader(socket.getInputStream(), ENCODING_GBK));

            while ((message = in.readLine()) != null) {
//                System.out.println(message);
//                System.out.println(new String(message.getBytes("UTF-8")));

                stringBuffer.append(message);
            }

            receiveString = stringBuffer.toString();
        } catch (UnknownHostException e) {
            log.error("没有找到服务器", e);
        } catch (IOException e) {
            log.error("与服务器通信出现异常", e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                log.error("关闭连接出现异常", e);
            }
        }

        log.info("客户端收到服务器返回的报文是:" + receiveString);
    }

    /**
     * 特殊字符转码
     *
     * @param value
     * @return
     */
    private static String encodeValue(String value) {
        value = value.replaceAll("&", "&amp;")
                .replaceAll("<", "&lt;")
                .replaceAll(">", "&gt;")
                .replaceAll("‘", "&apos;")
                .replaceAll("\"", "&quot;");
        return value;
    }

    /**
     * 特殊字符解码
     *
     * @param value
     * @return
     */
    public static String decodeValue(String value){
        value=value
        .replaceAll("&amp;", "&")
        .replaceAll("&lt;", "<")
        .replaceAll("&gt;", ">")
        .replaceAll("&apos;", "‘")
        .replaceAll("&quot;", "\"");
        return value;
    }

    /**
     * 解码 
 &#xXXXX;
     * @param str
     * @return
     */
    public static String decode4SoapValue(String value){
        value=value
        .replaceAll("&#xd", "\n")
        .replaceAll("&#x", "\\\\u")
        .replaceAll(";", "");
        value = decodeUnicode(value);
        return value;
    }

    /**
     * 解码 Unicode \\uXXXX
     * @param str
     * @return
     */
    public static String decodeUnicode(String str) {
        Charset set = Charset.forName("UTF-16");
        Pattern p = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
        Matcher m = p.matcher( str );
        int start = 0 ;
        int start2 = 0 ;
        StringBuffer sb = new StringBuffer();
        while( m.find( start ) ) {
            start2 = m.start() ;
            if( start2 > start ){
                String seg = str.substring(start, start2) ;
                sb.append( seg );
            }
            String code = m.group( 1 );
            int i = Integer.valueOf( code , 16 );
            byte[] bb = new byte[ 4 ] ;
            bb[ 0 ] = (byte) ((i >> 8) & 0xFF );
            bb[ 1 ] = (byte) ( i & 0xFF ) ;
            ByteBuffer b = ByteBuffer.wrap(bb);
            sb.append( String.valueOf( set.decode(b) ).trim() );
            start = m.end() ;
        }
        start2 = str.length() ;
        if( start2 > start ){
            String seg = str.substring(start, start2) ;
            sb.append( seg );
        }
        return sb.toString() ;
    }  

}

参考文章:

http://www.dnetzj.com/Content/329.html

时间: 2024-10-01 04:23:07

Web Service之Soap请求响应内容中文编码解密的相关文章

使用TcpTrace小工具截获Web Service的SOAP报文

Web Service客户端对服务端进行调用时,请求和响应都使用SOAP报文进行通讯.在开发和测试时,常常查看SOAP报文的内容,以便进行分析和调试.TcpTrace是一款比较小巧的工具,可以让我们截获TCP/IP协议上的报文,因为HTTP.JMS.STMP等协议都构建在TCP/IP基础上,所以可以很容易地截获Web Service的SOAP请求和响应报文.    我们实例中的Web Service运行于8080端口,可以让TcpTrace在8088端口上监听,并将8088端口监听的报文转发到8

iOS.访问 Web Service.同步GET请求方法

1.字符串转换为URL字符串NSString分类 #import <Foundation/Foundation.h> @interface NSString (URLEncoding) -(NSString *)URLEncodedString; -(NSString *)URLDecodedString; @end #import "T20140628013418NSString+URLEncoding.h" @implementation NSString (URLEn

Web service standards: SOAP, REST, OData, and more

Web service standards: SOAP, REST, OData, and more So far, we've covered the components of a web service, the messaging format and transport protocols. But in the eye of the developer, the development manager, and the IT professional,the real choice

iOS.访问 Web Service.异步GET请求方法

#import <UIKit/UIKit.h> #import "T20140628024750NSNumber+Message.h" #import "T20140628024750NSString+URLEncoding.h" @interface T20140628024750ViewController : UITableViewController<NSURLConnectionDelegate> @property (nonato

iOS.访问 Web Service.异步POST请求方法

#import <UIKit/UIKit.h> #import "T20140628024917NSNumber+Message.h" #import "T20140628024917NSString+URLEncoding.h" @interface T20140628024917ViewController : UITableViewController<NSURLConnectionDelegate> @property (nonato

建立自己的Web service(SOAP篇)

1.简介 这篇文章主要介绍采用SOAP来建立以及访问Web service接口. Web service是一个平台独立的,低耦合的,自包含的.基于可编程的web的应用程序,可使用开放的XML(标准通用标记语言下的一个子集)标准来描述.发布.发现.协调和配置这些应用程序,用于开发分布式的互操作的应用程序. Web Service技术, 能使得运行在不同机器上的不同应用无须借助附加的.专门的第三方软件或硬件, 就可相互交换数据或集成.依据Web Service规范实施的应用之间, 无论它们所使用的语

Web APi之捕获请求原始内容的实现方法以及接受POST请求多个参数多种解决方案(十四)

前言 我们知道在Web APi中捕获原始请求的内容是肯定是很容易的,但是这句话并不是完全正确,前面我们是不是讨论过,在Web APi中,如果对于字符串发出非Get请求我们则会出错,为何?因为Web APi对于简单的值不能很好的映射.之前我们谈论过请求内容注意事项问题,本节我们将更加深入的来讨论这个问题,我们会循序渐进进行探讨,并给出可行的解决方案,.细细品,定让你收货多多! 捕获请求原始内容实现方法 捕获复杂属性值 Web APi对于复杂属性值以JSON或者XML的形式成功发送到服务器,基于这点

ASP.NET Web Service 标准SOAP开发案例代码(自定义验证安全头SOAPHeader)

using System.Xml;using System.Xml.Serialization;using System.Web.Services.Protocols;using System.Configuration;using Service.Common.Constant; namespace Service.Common.Core.Head.Safe{    /// <summary>    /// 为了安全,自定义的Soap头    /// </summary>   

翻译-使用Spring调用SOAP Web Service

原文链接: http://spring.io/guides/gs/consuming-web-service/ 调用SOAP web service 本指南将指导你使用Spring调用一个基于SOAP的web service的整个过程. 指南内容 你将构建一个客户端,使用SOAP用来从远端的基于WSDL的web service获取天气数据.请访问http://wiki.cdyne.com/index.php/CDYNE_Weather进一步获取该天气服务的信息. 该服务根据邮编返回天气预测.你可