您的位置:首页 > 编程语言 > Java开发

C#调用java-ws(带身份验证功能)

2012-07-28 15:39 447 查看

java服务端:

服务接口:

@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld{
@WebMethod String getHelloWorldAsString();
}



服务实现:

@WebService(endpointInterface = "com.mkyong.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{
@Resource
WebServiceContext wsctx;

@Override
public String getHelloWorldAsString() {
MessageContext mctx = wsctx.getMessageContext();
//提取http header中的属性做权限判断
Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
List userList = (List) http_headers.get("Username");
List passList = (List) http_headers.get("Password");

String username = "";
String password = "";

if(userList!=null){
//get username
username = userList.get(0).toString();
}

if(passList!=null){
//get password
password = passList.get(0).toString();
}

//Should validate username and password with database
if (username.equals("mkyong") && password.equals("password")){
return "Hello World JAX-WS - Valid User!";
}else{
return "Unknown User!";
}
}
}


服务配置

/WebContent/WEB-INF/sun-jaxws.xml

<?xml version="1.0" encoding="UTF-8"?>

<endpoints

xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"

version="2.0">

<endpoint

name="HelloWorld"

implementation="com.mkyong.ws.HelloWorldImpl"

url-pattern="/hello"/>

</endpoints>

/WebContent/WEB-INF/web.xml

<web-app>
<listener>
<listener-class>
com.sun.xml.ws.transport.http.servlet.WSServletContextListener
</listener-class>
</listener>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>
com.sun.xml.ws.transport.http.servlet.WSServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

C#客户端

引用部署在tomcat中java web服务的地址(http://localhsot:8080/WebServices/hello?wsdl)生成代理类,在生成的代理类中重载GetWebRequest方法:

protected override System.Net.WebRequest GetWebRequest(Uri uri) {
System.Net.WebRequest request = base.GetWebRequest(uri);
request.Headers.Add("Username", "mkyong");
request.Headers.Add("Password", "password");

return request;
}


在客户端中调用:

localhost.HelloWorldImplService service = new TestCA.localhost.HelloWorldImplService();
MessageBox.Show(service.getHelloWorldAsString());


如果没有设置username和password或者设置错误,则调用时服务端方法会提示错误:



设置正确提示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐