Võ Văn Hải's blog

Chỉ có một điều tuyệt đối đó là mọi thứ đều tương đối…

Dùng ASP.Net truy xuất java Web Service

Trong ví dụ này, chúng ta có sử dụng bài viết  Web Service truy xuất cơ sở dữ liệu. và ta có thể tham khảo cách dùng JSP để truy xuất web wervice.

Khởi động visual studio.

1. Tạo mới 1 Web site bằng cách vào menu File->New->Web Site, chọn template là “ASP.NET Web Site“. Gõ tên Project là Access_javaWS. Mặc định ta sẽ có 1 trang Default.aspx, ta đổi tên lại thành Login.aspx.

2. Nhấn phải chuột lên Project chọn “Add Web Reference…“, một cửa sổ xuất hiện.

Copy rồi paste đường WSDL URL: http://localhost:8086/WS_DB/services/LogonService?wsdl vào mục URL, nhấn GO. Kết quả như sau:
https://vovanhai.files.wordpress.com/2008/10/aspjavaws1.png

Có thể đặt lại tên cho tham chiếu thay vì localhost, ở đây tôi không đổi tên.

Nhấn nút “Add Reference” để thêm tham chiếu vào project.

Thiết kế giao diện cho trang login

<%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”Login.aspx.cs” Inherits=”_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>

<table style=”width:70%;”>
<tr>
<td align=”right”>User Name:</td><td>
<asp:TextBox ID=”txtUserName” runat=”server” Width=”188px”></asp:TextBox>
</td>
</tr>
<tr>
<td align=”right”>
Password</td>
<td>
<asp:TextBox ID=”txtPSW” runat=”server” Width=”188px” TextMode=”Password”></asp:TextBox>
</td>
</tr>
<tr>
<td align=”right”>
<asp:Button ID=”btnLogon” runat=”server” Text=”Logon”
onclick=”btnLogon_Click” />
</td>
<td>
<asp:Button ID=”btnReset” runat=”server” Text=”Reset”
onclick=”btnReset_Click” />
</td>
</tr>
</table>

</div>
</form>
</body>
</html>

Giao diện trang Success.aspx

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Success.aspx.cs” Inherits=”Success” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<h1>Successful</h1>
</div>
</form>
</body>
</html>

Giao diện trang Failed.aspx

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Failed.aspx.cs” Inherits=”Failed” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<h1>FAILED</h1>
</div>
</form>
</body>
</html>

Code sử dụng đăng nhập và reset của trang Login.aspx

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnLogon_Click(object sender, EventArgs e)
{
localhost.LogonService svr = new localhost.LogonService();
int ret = 0;
bool b = true;
svr.Logon(txtUserName.Text, txtPSW.Text, out ret, out b);
if (ret == 1)
Response.Redirect(“Success.aspx”);
else
Response.Redirect(“Failed.aspx”);
}
protected void btnReset_Click(object sender, EventArgs e)
{
txtPSW.Text = “”;
txtUserName.Text = “”;
}
}

Kết quả thực thi
https://vovanhai.files.wordpress.com/2008/10/aspjavaws2.png

Chúc các bạn thành công!

7 Responses to “Dùng ASP.Net truy xuất java Web Service”

  1. Tuan said

    Bài này sư phụ viết rất hay. Cho em hỏi có cách nào add động cái web service mà không dùng cái ‘add web ference’ trong Visual Studio như trên ko? Em có 1 đoạn code mẩu mà đọc xong thấy stress quá, không bit làm gì nửa. :). Anh xem thử dùm được ko?
    Code mẩu:
    public object CallWebService(string webServiceAsmxUrl, string serviceName, string methodName, object[] args)
    {
    System.Net.WebClient client = new System.Net.WebClient();
    // Connect To the web service
    System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + “?wsdl”);
    // Now read the WSDL file describing a service.
    ServiceDescription description = ServiceDescription.Read(stream);
    ///// LOAD THE DOM /////////
    // Initialize a service description importer.
    ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
    importer.ProtocolName = “Soap12”; // Use SOAP 1.2.
    importer.AddServiceDescription(description, null, null);
    // Generate a proxy client.
    importer.Style = ServiceDescriptionImportStyle.Client;
    // Generate properties to represent primitive values.
    importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
    // Initialize a Code-DOM tree into which we will import the service.
    CodeNamespace nmspace = new CodeNamespace();
    CodeCompileUnit unit1 = new CodeCompileUnit();
    unit1.Namespaces.Add(nmspace);
    // Import the service into the Code-DOM tree. This creates proxy code that uses the service.
    ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
    if (warning == 0) // If zero then we are good to go
    {
    // Generate the proxy code
    CodeDomProvider provider1 = CodeDomProvider.CreateProvider(“CSharp”);
    // Compile the assembly proxy with the appropriate references
    string[] assemblyReferences = new string[5] { “System.dll”, “System.Web.Services.dll”, “System.Web.dll”, “System.Xml.dll”, “System.Data.dll” };
    CompilerParameters parms = new CompilerParameters(assemblyReferences);
    CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
    // Check For Errors
    if (results.Errors.Count > 0)
    {
    foreach (CompilerError oops in results.Errors)
    {
    System.Diagnostics.Debug.WriteLine(“========Compiler error============”);
    System.Diagnostics.Debug.WriteLine(oops.ErrorText);
    }
    throw new System.Exception(“Compile Error Occured calling webservice. Check Debug ouput window.”);
    }
    // Finally, Invoke the web service method
    object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
    MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
    return mi.Invoke(wsvcClass, args);
    }
    else
    {
    return null;
    }

  2. Tuan said

    Bài này sư phụ viết rất hay. Cho em hỏi có cách nào add động cái web service mà không dùng cái ‘add web ference’ trong Visual Studio như trên ko? Em có 1 đoạn code mẩu mà đọc xong thấy stress quá, không bit làm gì nửa. 🙂

  3. cảm ơn bác nhé! bài viết rất hay

  4. Hien said

    Thầy ơi, thầy chỉ giúp dùm e cách dùng .net kết nối java web service = https:// nhé. Thanks.

  5. Nguyễn Đức Hoàng said

    Thầy ơi :((
    Em không thể add cái 4 tham số như thầy được .
    svr.Logon(txtUserName.Text, txtPSW.Text, out ret, out b);
    nó nói không có phương thức nạp chồng ( overload ) với 4 tham số .
    Còn em gọi 2 tham số thôi thì không thể lấy kết quả trả về . Mong thầy giúp đỡ .

  6. Thành said

    Cám ơn bài viết trên của Thầy, thầy Hải có thể viết 1 ví dụ sử dụng Axis Webservice trả về một mảng các đối tượng cho C# client được không. Hoặc thầy có thể cho em hướng để tìm hiểu được không thầy. Cảm ơn thầy

  7. khivq said

    Hi anh!
    Cho em hỏi, nếu webservice có cấu hình authen (có user/pass) thì mình gọi thế nào?

    Cảm ơn anh!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.