首页 > 代码库 > Web Service之Soap请求响应内容中文编码解密

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;    }        /**      * 解码 &#xd; &#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() ;      }      }
View Code

 

参考文章:
http://www.dnetzj.com/Content/329.html

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