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

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("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("'", "'")
.replaceAll("\"", """);
return value;
} /**
* 特殊字符解码
*
* @param value
* @return
*/
public static String decodeValue(String value){
value=value
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("'", "'")
.replaceAll(""", "\"");
return value;
} /**
* 解码 &#xXXXX;
* @param str
* @return
*/
public static String decode4SoapValue(String value){
value=value
.replaceAll("
", "\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() ;
} }
Web Service之Soap请求响应内容中文编码解密的更多相关文章
- 使用TcpTrace小工具截获Web Service的SOAP报文
Web Service客户端对服务端进行调用时,请求和响应都使用SOAP报文进行通讯.在开发和测试时,常常查看SOAP报文的内容,以便进行分析和调试.TcpTrace是一款比较小巧的工具,可以让我们截 ...
- 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 ser ...
- 建立自己的Web service(SOAP篇)
1.简介 这篇文章主要介绍采用SOAP来建立以及访问Web service接口. Web service是一个平台独立的,低耦合的,自包含的.基于可编程的web的应用程序,可使用开放的XML(标准通用 ...
- Web APi之捕获请求原始内容的实现方法以及接受POST请求多个参数多种解决方案(十四)
前言 我们知道在Web APi中捕获原始请求的内容是肯定是很容易的,但是这句话并不是完全正确,前面我们是不是讨论过,在Web APi中,如果对于字符串发出非Get请求我们则会出错,为何?因为Web A ...
- 几种远程调用接口协议简单比较和web service(SOAP)与HTTP接口的区别:
什么是web service? 答:soap请求是HTTP POST的一个专用版本,遵循一种特殊的xml消息格式Content-type设置为: text/xml任何数据都可以xml化. ...
- nginx配置打印请求响应内容
#放在http{}里面 log_format kyh ' [$time_local] "$request" $status \n' 'req_header:"$req_h ...
- Jmeter——请求响应内容乱码解决办法
前段时间,换过一次设备,重新下载了Jmeter.有一次在编写脚本时,响应内容中的中文一直显示乱码. 遇到乱码不要慌,肯定是有办法来解决的.具体解决办法,可以参考之前的博文,Jmeter--BeanSh ...
- ASP.NET Web Service 标准SOAP开发案例代码(自定义验证安全头SOAPHeader)
using System.Xml;using System.Xml.Serialization;using System.Web.Services.Protocols;using System.Con ...
- http协议请求响应内容示例
POST http://www.cytxl.com.cn/api/common/login.php?XDEBUG_SESSION_START=netbeans-xdebug HTTP/1.1 Host ...
随机推荐
- [SDOI2010] 所驼门王的宝藏 [建图+tarjan缩点+DAG dp]
题面传送门: 传送门 思路: 看完题建模,容易得出是求单向图最长路径的问题 那么把这张图缩强联通分量,再在DAG上面DP即可 然而 这道题的建图实际上才是真正的考点 如果对于每一个点都直接连边到它所有 ...
- bootstrap之常见组件应用1
bootstrap中,常见的组件有很多,比如按钮,输入框,导航条,巨幕,面板等.这次根据对bootstrap的一系列学习进行总结. 按钮:button <button type="bu ...
- BZOJ3612 [Heoi2014]平衡 整数划分
[Heoi2014]平衡 Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 348 Solved: 273[Submit][Status][Discus ...
- [暑假集训--数论]poj2034 Anti-prime Sequences
Given a sequence of consecutive integers n,n+1,n+2,...,m, an anti-prime sequence is a rearrangement ...
- nodeJS学习(7)--- WS开发 NodeJS 项目-节2 <安装&设置&启动 mongodb 数据库++遇到的问题>
本文系统 win7 参考:http://lib.csdn.net/article/mongodb/58097 http://www.cnblogs.com/lzrabbit/p/3682510.ht ...
- spring rest 请求怎样添加Basic Auth请求頭
请自行揣摩代码 package com.hudai.platform.manager.util; import java.net.URI; import java.net.URISyntaxExcep ...
- 【HDOJ5520】Number Link(费用流)
题意:NxM的格子有些上面有数字,现在要把奇数跟偶数配对连起来,其他的格子连成一个个回路, 单独的相邻两个格子相连也算是一个回路按两条边算,连线不能相交, 给出相邻两个格子相连的费用,求最小的总费用, ...
- Visual Studio 试用版的评估期已经结束【解决方案】
原文发布时间为:2010-01-09 -- 来源于本人的百度文章 [由搬家工具导入] Visual Studio 试用版的评估期已经结束…… 解决。2010年1月9日0:02:50,本人亲自尝试,可行 ...
- 原生app与js交互 jsSDK设计
var UA = window.navigator.userAgent.toLowerCase()var isIOS = UA && /iphone|ipad|ipod|ios/.te ...
- phpexcel--导入excel表格
最近在做一个小项目,就是一个管理信息的小系统:要求有导入和导出的信息为excel的功能,研究过导入导出功能的肯定知道导出要比导入的简单多了,导入用的phpexcel,当时对phpexcel是完全不了解 ...