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 ...
随机推荐
- hdu5834 Magic boy Bi Luo with his excited tree 【树形dp】
题目链接 hdu5834 题解 思路很粗犷,实现很难受 设\(f[i][0|1]\)表示向子树走回来或不回来的最大收益 设\(g[i][0|1]\)表示向父亲走走回来或不回来的最大收益 再设\(h[i ...
- Apache+Openssl
Apache编译还需要一些依赖: #./configure --prefix……检查编辑环境时出现: checking for APR... no configure: error: APR not ...
- 球形空间产生器sphere(bzoj 1013)
Description 有一个球形空间产生器能够在n维空间中产生一个坚硬的球体.现在,你被困在了这个n维球体中,你只知道球面上n+1个点的坐标,你需要以最快的速度确定这个n维球体的球心坐标,以便于摧毁 ...
- pat 甲级 Public Bike Management
Public Bike Management (30) 题目描述 There is a public bike service in Hangzhou City which provides grea ...
- python转exe2
转载自 xiake200704 最终编辑 xiake200704 一.简介 py2exe是一个将python脚本转换成windows上的可独立执行的可执行程序(*.exe)的工具,这样,你 ...
- 洛谷P1279 字串距离
题目描述 设有字符串X,我们称在X的头尾及中间插入任意多个空格后构成的新字符串为X的扩展串,如字符串X为”abcbcd”,则字符串“abcb□cd”,“□a□bcbcd□”和“abcb□cd□”都是X ...
- updatepanel的使用【他人经验+原创 完整例子】
原文发布时间为:2009-05-16 -- 来源于本人的百度文章 [由搬家工具导入] 刚上传的代码,不知道能不能下载:[源码包含所有ajax控件的简单使用] http://www.xmaspx.com ...
- 远程连接linux和linux的网络配置
linux一般是作为服务器的,并不直接对其进行操作,并且由于地理位置的原因,我们需要对linux服务器进行远程连接. 首先我们要确定linux服务器是否安装了ssh服务,在linux服务器上安装ope ...
- 【jetty】Jetty与Tomcat的区别
Jetty 的架构从前面的分析可知,它的所有组件都是基于 Handler 来实现,当然它也支持 JMX.但是主要的功能扩展都可以用 Handler 来实现.可以说 Jetty 是面向 Handler ...
- Django之model F/Q以及多对多操作
model之F/Q操作 F操作,使用查询条件的值 打个比方吧,有一张表,保存着公司员工的工资,公司普涨工资,如何在model中操作,这就用到了F,首先需要导入此模块: from django.db.m ...