最近使用c#调用另外一个同事写的java webservice耽误了很多时间,网上资料不太完整,走了很多弯路,希望对大家有帮助。

基本思路是
1.拼装soap使用http post ,主要将验证身份信息放入header中,以下code供参考:8-15行内用户、密码,其他soap信息需要根据自己的service修改,

可以使用soapui获取到body以及xmlns信息


 1 public class InvokeServiceWithSoap
 2     {
 3         public static void InvokeService()
 4         {
 5             StringBuilder soap = new StringBuilder();
 6             soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
 7             soap.Append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:end=\"http://localhost/service/\">");
 8             soap.Append("<soapenv:Header>");
 9             soap.Append("<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">");
10             soap.Append("<wsse:UsernameToken>");
11             soap.Append("<wsse:Username>username</wsse:Username>");//用户名
12             soap.Append("<wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">password</wsse:Password>");//口令
13             soap.Append("</wsse:UsernameToken>");
14             soap.Append("</wsse:Security>");
15             soap.Append("</soapenv:Header>");
16             soap.Append("<soapenv:Body>");
17             soap.Append("<end:service1>");
18             soap.Append("<arg0></arg0>");
19             soap.Append("</end:service1>");
20             soap.Append(" </soapenv:Body>");
21             soap.Append(" </soapenv:Envelope>");
22 
23             string url = "http://localhost/end:service1";
24             var result = GetSOAPReSource(url, soap.ToString());
25 
26         }
27 
28         public static string GetSOAPReSource(string url, string datastr)
29         {
30             try
31             {
32                 //request
33                 Uri uri = new Uri(url);
34                 WebRequest webRequest = WebRequest.Create(uri);
35                 webRequest.ContentType = "text/xml; charset=utf-8";
36                 webRequest.Method = "POST";
37                 using (Stream requestStream = webRequest.GetRequestStream())
38                 {
39                     byte[] paramBytes = Encoding.UTF8.GetBytes(datastr.ToString());
40                     requestStream.Write(paramBytes, 0, paramBytes.Length);
41                 }
42                 //response
43                 WebResponse webResponse = webRequest.GetResponse();
44                 using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
45                 {
46                     string result = "";
47                     return result = myStreamReader.ReadToEnd();
48                 }
49 
50             }
51             catch (Exception ex)
52             {
53                 throw ex;
54             }
55 
56         }
57 
58     }

2.使用wsdl生成代理类,代理类重写HttpRequest ,将安全验证信息增加到request中,也没有测试通过


 1  protected override System.Net.WebRequest GetWebRequest(Uri uri)
 2         {
 3             System.Net.WebRequest request= base.GetWebRequest(uri);
 4             System.Net.NetworkCredential nc = new System.Net.NetworkCredential();
 5             nc.UserName = "ssotest";//java webservice 用户名  
 6             nc.Password = "ssotest";//java webservice 密码  
 7             request.Credentials = nc;
 8             
 9             return request;
10         }
下面说一个比较简单的方法:
直接使用.net中的服务引用,注意是服务引用(类似WCF引用)主要通过servicemodel来设置安全认证信息,framework3.0以上都支持,
引用后将 Config中 servicemodel 的 endpoint  节点 增加headers ,安全验证信息增加尽量来即可。
以下是完整的config:

 1 <system.serviceModel>
 2     <bindings>
 3       <basicHttpBinding>
 4         <binding name="Service1SoapBinding" maxReceivedMessageSize="99999999"/>
 5       </basicHttpBinding>
 6     </bindings>
 7     <client>
 8         <endpoint address="http://local:9090/ Service1"
 9           binding="basicHttpBinding" bindingConfiguration="onlineUserServiceSoapBinding"
10           contract="smpwcf.Service1" name="Service1ImplPort" >
11             <headers>
12                 <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
13                     <wsse:UsernameToken>
14                         <wsse:Username>username</wsse:Username>
15                         <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">password</wsse:Password>
16                     </wsse:UsernameToken>
17                 </wsse:Security>
18             </headers>
19         </endpoint>
20     </client> 21   </system.serviceModel>

另外附加一段php soap调用java wsse webservice代码 (已经测试通过)

<?php


//Soap Request
class WSSESoapClient extends SoapClient {                                                                                           
    protected $wsseUser;
    protected $wssePassword;     public function setWSSECredentials($user, $password) {
        $this->wsseUser = $user;
        $this->wssePassword = $password;
    }     public function __doRequest($request, $location, $action, $version)
           {
        try
        {
        if (!$this->wsseUser or !$this->wssePassword)
          {
                   return parent::__doRequest($request, $location, $action, $version);
              }         // get SOAP message into DOM
        $dom = new DOMDocument();
        $dom->loadXML($request);
        $xp = new DOMXPath($dom);
        $xp->registerNamespace('soapenv', 'http://schemas.xmlsoap.org/soap/envelope/');
    
        // search for SOAP header, create one if not found
        $header = $xp->query('/soapenv:Envelope/soapenv:Header')->item(0);
    if (!$header)
           {
            $header = $dom->createElementNS('http://schemas.xmlsoap.org/soap/envelope/', 'soapenv:Header');
            $envelope = $xp->query('/soapenv:Envelope')->item(0);
            $envelope->insertBefore($header, $xp->query('/soapenv:Envelope/soapenv:Body')->item(0));
        }     // add WSSE header 
    $security = $dom->createElementNS('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'wsse:Security');
        $usernameToken = $dom->createElementNS('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'wsse:UsernameToken');
        $username = $dom->createElementNS('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'wsse:Username', $this->wsseUser);
    $password = $dom->createElementNS('http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'wsse:Password', $this->wssePassword);
    $password->setAttribute( "Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText" );
    $security->appendChild($usernameToken);
    $usernameToken->appendChild($username);
        $usernameToken->appendChild($password);
        $header->appendChild($security);         // perform SOAP call
    $request = $dom->saveXML();
//    echo $request;
        return parent::__doRequest($request, $location, $action, $version);
    }
      catch (Exception $e)
      {
           echo "<h2>Post Method Error!</h2>"; 
            echo $e->getMessage(); 
      }
    } } 
  //build soap
try{
    $clientsoap = new WSSESoapClient("http://localhost/service1?wsdl");
    $clientsoap->setWSSECredentials("username","password");
//    $clientsoap->soap_defencoding = 'utf-8';
//    $clientsoap->decode_utf8 = false;
    //soap xml
    $request="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:end=\"http://localhost/service1/\">"."<soapenv:Body>"."<end:service1>"."<arg0>参数</arg0>"."</end:service1>"."</soapenv:Body>"."</soapenv:Envelope>";
    $location="http://172.16.2.31:9090/smp/ws/onlineuserservice";
    $action=null;
           $version=0;
    $result =$clientsoap->__doRequest($request,$location,$action,$version);
    echo $result;
}
catch (Exception $e) { 
            echo "<h2>Exception Error!</h2>"; 
            echo $e->getMessage(); 
        } 
?>

c#调用带有安全认证的java webservice的更多相关文章

  1. java servlet调用带有多个返回结果集的存储过程

    一.mysql存储过程 这里我先说下我这个功能实现的逻辑及途中遇到的一些问题.这个存储过程一共带两个输入参数,一共关联到两张表的查询,每个参数都对应查询表中的一个判断,所以一共返回了两个结果集(当然要 ...

  2. java Servlet+mysql 调用带有输入参数和返回值的存储过程(原创)

    这个数据访问的功能,我在.NET+Mysql .NET+Sqlserver  PHP+Mysql上都实现过,并且都发布在了我博客园里面,因为我觉得这个功能实在是太重要,会让你少写很多SQL语句不说,还 ...

  3. JAVA 调用Axis2 code generator 生成的webservice

    以下代码为调用 JAVA 调用Axis2 code generator 生成的webservice的代码. package test; import java.rmi.RemoteException; ...

  4. Java WebService接口生成和调用 图文详解>【转】【待调整】

    webservice简介: Web Service技术, 能使得运行在不同机器上的不同应用无须借助附加的.专门的第三方软件或硬件, 就可相互交换数据或集成.依据Web Service规范实施的应用之间 ...

  5. Java WebService 开发简单实例

    Web Service 是一种新的web应用程序分支,他们是自包含.自描述.模块化的应用,可以发布.定位.通过web调用.Web Service可以执行从简单的请求到复杂商务处理的任何功能.一旦部署以 ...

  6. paip.myeclipse7 java webservice 最佳实践o228

    paip.myeclipse7  java webservice 最佳实践o228 java的ws实现方案:jax-ws>>xfire ws的测试工具  webservice测试调用工具W ...

  7. MAXIMO系统 java webservice 中PDA移动应用系统开发

    MAXIMO系统 java webservice 中PDA移动应用系统开发  平时经常用的wince PDA手持设备调用c#写的webservice, 当然PDA也可以调用java webservic ...

  8. java webservice的多种实现方法汇总

    一.基于EJB容器管理webservice :     1.首先建立一个Web services EndPoint: package cn.test.service.impl; import java ...

  9. [Java] webservice soap,wsdl 例子

    java 调用webservice的各种方法总结 现在webservice加xml技术已经逐渐成熟,但要真正要用起来还需时日!! 由于毕业设计缘故,我看了很多关于webservice方面的知识,今天和 ...

随机推荐

  1. leetcode Insert Interval 区间插入

    作者:jostree  转载请注明出处 http://www.cnblogs.com/jostree/p/4051169.html 题目链接:leetcode Insert Interval 使用模拟 ...

  2. linux 终端快捷键

    1. 移动光标快捷键 ctrl+f 向前移动一个字符 ctrl+b 向后移动一个字符 alt+f 向前移动一个单词 alt+b 向后移动一个单词 ctrl+a 移动到当前行首 ctrl+e 移动到当前 ...

  3. iOS中XML的相关知识

    1.什么是XML “当 XML(扩展标记语言)于 1998 年 2 月被引入软件工业界时,它给整个行业带来了一场风暴.有史以来第一次,这个世界拥有了一种用来结构化文档和数据的通用且适应性强的格式,它不 ...

  4. 一个基本jquery的评论留言模块

    <div class="productDiscuss"> <div class="title"><span class=" ...

  5. mysql 高性能

    第一章节:共享锁(读锁),排他锁(写锁) 查询数据表所使用的存储引擎:show table status like '表名' \G 转换数据表的存储引擎:alter table 表名 engine=引 ...

  6. quality center的使用简介

    quality center是一个基于Web的测试管理工具,其实是伪B/S的软件,可以组织和管理应用程序测试流程的所有阶段,包括制定测试需求.计划测试.执行测试和跟踪缺陷.此外,通过Quality C ...

  7. php新特性--持续更新

    命名空间 在其他语言中不算新鲜事,但php是5.3.0中引入,具体定义就不复述了,其主要作用是 封装和组织相关php类 .命名空间被引入之前php主要是通过Zend方式组织代码,这种方式带来的问题是类 ...

  8. Maven插件实现的autoconfig机制(转)

    autoconfig这种机制在软件开发和发布的过程中是非常方便也是非常必要的一种动态替换配置信息的一种手段,一种很贴切的比喻:这个就像在windows下面安装一个软件时,我们按照安装向导给我们弹出提示 ...

  9. Nginx+Keepalived主备负载均衡

    实验环境及软件版本: CentOS版本:    6.6(2.6.32.-504.el6.x86_64) nginx版本:     nginx-1.6.2 keepalived版本:keepalived ...

  10. python基础学习(二)--函数

    return返回值: python函数都有返回值,函数体内无return,默认返回值None, 函数参数: 1.普通参数 严格按照顺序,将实际参数赋值给形式参数,一一对应. 例: def send(x ...