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 ...
随机推荐
- JAVA File方法文本复制读写-解决中文乱码
import java.io.*; public class TextFile { public static void main(String[] args) throws Exception { ...
- 小程序红包开发跳坑记 微信小程序红包接口开发过程中遇到的问题 微信小程序红包开发
现在做小程序的越来越多,商家推广也是一个瓶颈,谁不发点红包,都很难找到人来用你的微信小程序了.于是不管你开发什么小程序功能,你或多或少都要用到小程序来发红包吧. 我们自己之前做公众号发红包,做了两三 ...
- Python之时间:datetime模块
datetime在time基础之上封装了一些方法.但是time是经常使用的,datetime中的功能,time都能实现 一.datetime的三个模块 datetime.date datetime.t ...
- source ~/.bashrc 什么意思
source:使当前shell读入路径为filepath的shell文件并依次执行文件中的所有语句,通常用于重新执行刚修改的初始化文件,使之立即生效,而不必注销并重新登录 https://www.cn ...
- 利用GridView控件导出其他文件(导出Excel,导出Word文件)
原文发布时间为:2008-10-16 -- 来源于本人的百度文章 [由搬家工具导入] // 注意,在Visual Studio2005平台下,如果使用GridView导出文件, //就必须重 ...
- DB迁移:从SQL Server 2005到MySQL
一.工具选择 依工作需要进行老产品升级,其中一项重要工作就是将SQL Server数据库改为MySQL数据库,故而在对<各种主流 SQLServer 迁移到 MySQL 工具对比>文章学习 ...
- request库
0x00 环境简介和安装 我这里使用的是python2.7版本,直接使用pycharm2018这款IDE. 首先在pycharm中配置一下virtualenv环境,virtualenv是一个创建独立 ...
- 《Linux命令行与shell脚本编程大全 第3版》Linux命令行---4
以下为阅读<Linux命令行与shell脚本编程大全 第3版>的读书笔记,为了方便记录,特地与书的内容保持同步,特意做成一节一次随笔,特记录如下: <Linux命令行与shell脚本 ...
- EasyUI左边树菜单和datagrid分页
//这个页面是Home.html 1 <!DOCTYPE html> <html> <head> <meta http-equiv="Content ...
- JWT在PHP使用及问题处理
官网 https://jwt.io/ 3.0版本 https://github.com/lcobucci/jwt 安装 composer require lcobucci/jwt 依赖 PHP 5.5 ...