How to call webservice in php _ PHP Tutorial

Source: Internet
Author: User
Tags soap client stock prices
Introduction to how php calls webservice applications. 1.1 Basic Concept of WebService is also called XMLWebServiceWebService. it is a lightweight and independent service that can receive requests sent from other systems on the Internet or Intranet. 1.1 Basic concepts of Web Service

Web Service, also known as XML Web Service WebService, is a lightweight independent communication technology that can receive requests from other systems on the Internet or Intranet. Yes: the software services provided on the Web through SOAP are described using the WSDL file and registered through UDDI.

XML :( Extensible Markup Language) extended Markup Language. Short-term-oriented temporary data processing and HiChina network are the basis of Soap.

Soap: (Simple Object Access Protocol) Simple Object Access Protocol. Is the communication protocol of XML Web Service. After you find your WSDL description document through UDDI, you can use SOAP to call one or more operations in your Web service. SOAP is a standard for calling methods in XML format. it supports different underlying interfaces, such as HTTP (S) or SMTP.

WSDL :( Web Services Description Language) the WSDL file is an XML document that describes a group of SOAP messages and how to exchange them. In most cases, it is automatically generated and used by the software.

UDDI (Universal Description, Discovery, and Integration) is a new project mainly for Web service providers and users. Before you can call a Web service, you must determine the business methods contained in the service, find the called interface definition, and compile software on the server, UDDI is a mechanism that guides the system to find the corresponding service based on the description document. UDDI uses the SOAP message mechanism (standard XML/HTTP) to publish, edit, browse, and find registration information. It uses XML format to encapsulate different types of data and sends the data to the registration center or the registration center to return the required data.

1.2 XML Web Service features

The main goal of Web Service is cross-platform interoperability. To achieve this goal, Web services are fully based on standards independent of the platform and software vendors, such as XML (Extensible Markup Language) and XSD (XML Schema, is a new platform for creating interoperable and distributed applications. Therefore, using Web Service has many advantages:

1. Cross-firewall communication

If the application has thousands of users distributed all over the world, communication between the client and the server will be a tough problem. Because there is usually a firewall or proxy server between the client and the server. The traditional approach is to use a browser as the client, write a lot of ASP pages, and expose the middle layer of the application to the end user. The result is that development is difficult and programs are difficult to maintain. If the client code is no longer so dependent on HTML forms, the client programming will be much simpler. If the intermediate layer component is changed to Web Service, you can directly call the intermediate layer component from the user interface, thus saving the step for creating an ASP page. To call a Web Service, you can directly use a SOAP client such as Microsoft SOAP Toolkit or. net, or use a self-developed SOAP client to connect it to the application. This not only shortens the development cycle, but also reduces code complexity and enhances the maintainability of applications. At the same time, the application does not need to jump to the corresponding "result page" every time it calls the middle layer components ".

2. Application Integration

Enterprise-level application developers know that enterprises often need to integrate various programs written in different languages and run on different platforms, this integration will take a lot of development effort. Applications often need to obtain data from programs on a running host, or send data to the host or other platform applications. Even on the same platform, various software products produced by different software vendors often need to be integrated. Through Web Service, applications can use standard methods to "expose" functions and data for other applications.

XML Web services provides the ability to exchange messages using standard protocols (HTTP, XML, SOAP, and WSDL) in a loosely coupled environment. Messages can be structured, typed, or loosely defined.

3. B2B integration

B2B refers to Business, as in businesses doing business with other businesses, the e-commerce of merchants (generally referred to as enterprises, that is, products, services, and information exchange between enterprises over the Internet. The popular saying means that both the supply and demand sides of e-commerce transactions are merchants (or enterprises or companies). they use Internet technology or various business network platforms to complete the business transaction process.

Web Service is the key to successful B2B integration. With Web Service, the company only needs to expose key business applications to specified suppliers and customers, and the Web Service runs on the Internet, it can be easily implemented anywhere in the world, and its operation cost is relatively low. Web Service is only a key part of B2B integration, and many other parts are required for integration. The biggest benefit of implementing B2B integration with Web services is that it can easily implement interoperability. As long as the business logic is exposed and becomes a Web Service, any designated partner can call these business logic, regardless of the platform on which their system runs, the development language used. This greatly reduces the time and cost spent on B2B integration.

4. software and data reuse

Web Service allows code reuse while reusing the data behind the code. When using Web services, you no longer have to purchase and install software components from a third party, as before, and then call these components from the application; you only need to directly call the remote Web Service. Another case of software reuse is to integrate the functions of several applications and expose them through Web services, you can easily integrate all these functions into your portal to provide users with a unified and friendly interface. You can use the functions provided by third-party Web services in applications, or provide your own application functions to others through Web services. In both cases, you can reuse the data behind the code and code.

From the above discussion, we can see that Web services are most useful when performing interoperability or remote calls through the Web. However, in some cases, Web services cannot bring any benefits at all. Web services have the following disadvantages:

1. standalone applications

Currently, enterprises and individuals still use many desktop applications. Some of them only need to communicate with other programs on the local machine. In this case, it is best not to use Web services, as long as you use local APIs. COM is very suitable for working in this case because it is small and fast. The same is true for the software running on the same server. Of course, Web services can also be used in these scenarios, but that will not only consume too much, but will not bring any benefits.

2. LAN applications

In many applications, all programs use COM on the Windows platform and run on the same LAN. In these programs, using DCOM is much more effective than SOAP/HTTP. Similarly, if a. net program is to connect to another. net program on the LAN, it should use. net Remoting. In fact, in. net Remoting, you can also specify the use of SOAP/HTTP for Web Service calls. However, it is better to call RPC directly through TCP, which will be much more effective.

1.3 XML Web Service applications

1. the original XML Web Service is usually a source of information that can be easily incorporated into applications, such as stock prices, weather forecasts, and sports scores.

2. provide existing applications in XML Web Service mode, build new and more powerful applications, and use XML Web Service as the construction block.

For example, a user can develop a purchase application to automatically obtain price information from different suppliers, so that the user can select a supplier, submit an order, and then track the transportation of the goods until the goods are received. In addition to providing services on the Web, supplier applications can also use XML Web Service to check the customer's credit, collect the payment, and handle the freight formalities with the freight company.

2. Web Service development

The. net platform has built-in support for Web services, including the construction and use of Web services. Unlike other development platforms, you can use the. net platform to develop Web services without other tools or SDKs .. Net Framework itself fully supports Web services, including server-side request processors and support for sending and receiving SOAP messages to clients. Next, we will use Microsoft Visual Studio. net 20058 (VS. Net 2008) to create and use a simple Web Service.

2.1 create a simple Web Service

First, open VS2005, open "file-new-website", and select "ASP. NET Web Service"

Check the Service. cs code and you will find that VS. Net 2005 has already set up a default framework for the Web Service file. The original code is:

The code is as follows:

Using System;
Using System. Linq;
Using System. Web;
Using System. Web. Services;
Using System. Web. Services. Protocols;
Using System. Xml. Linq;
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
// To allow ASP. net ajax to call this Web service from a script, cancel the comments to the downstream.
// [System. Web. Script. Services. ScriptService]
Public class Service: System. Web. Services. WebService
{
Public Service (){
// If you use the designed component, uncomment the following line
// InitializeComponent ();
}
[WebMethod]
Public string HelloWorld ()
{
Return "Hello World ";
}
}
Using System;
Using System. Linq;
Using System. Web;
Using System. Web. Services;
Using System. Web. Services. Protocols;
Using System. Xml. Linq;
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
// To allow ASP. net ajax to call this Web service from a script, cancel the comments to the downstream.
// [System. Web. Script. Services. ScriptService]
Public class Service: System. Web. Services. WebService
{
Public Service (){
// If you use the designed component, uncomment the following line
// InitializeComponent ();
}
[WebMethod]
Public string HelloWorld ()
{
Return "Hello World ";
}
}

There is already a Hello World method in the default project. run it directly to see the effect,

Click the "HelloWorld" hyperlink on the displayed page to jump to the next page:

Click the "call" button to view the Web Service results returned in XML format. It indicates that our Web Service environment is correct, and we have initially come into contact with the simplest Web Service.

2.2 Create a simple and functional Web Service

We have learned about webservice at a macro level. In fact, webservice is an external interface, which contains functions that can be called by external customers (note: There are also functions that cannot be called by customers ). if we are a server, we have written a webservice and then gave it to the customer (and we also gave them the call rules ), the customer can be in a relatively transparent state when obtaining information from the server. that is, the customer does not understand (or need to) the process, and they only obtain data. in the code file, if we want this function to become an externally callable interface function after writing a function, we must add a line of code [WebMethod (Description = "function Description")] to the function. if your function does not have this declaration, it cannot be referenced by users. next, let's write a simple Web Service example.

First, comment out the default HelloWorld method, and simply write the four methods for finding addition, subtraction, multiplication, division, and so on;

The code is as follows:

Using System;
Using System. Linq;
Using System. Web;
Using System. Web. Services;
Using System. Web. Services. Protocols;
Using System. Xml. Linq;
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
// To allow ASP. net ajax to call this Web service from a script, cancel the comments to the downstream.
// [System. Web. Script. Services. ScriptService]
Public class Service: System. Web. Services. WebService
{
Public Service (){
// If you use the designed component, uncomment the following line
// InitializeComponent ();
}
// [WebMethod]
// Public string HelloWorld ()
//{
// Return "Hello World ";
//}
[WebMethod (Description = "summation method")]
Public double addition (double I, double j)
{
Return I + j;
}
[WebMethod (Description = "difference calculation method")]
Public double subtract (double I, double j)
{
Return I-j;
}
[WebMethod (Description = "method for product calculation")]
Public double multiplication (double I, double j)
{
Return I * j;
}
[WebMethod (Description = "method of quotient calculation")]
Public double pision (double I, double j)
{
If (j! = 0)
Return I/j;
Else
Return 0;
}
}


The code is as follows:

Using System;
Using System. Linq;
Using System. Web;
Using System. Web. Services;
Using System. Web. Services. Protocols;
Using System. Xml. Linq;
[WebService (Namespace = "http://tempuri.org/")]
[WebServiceBinding (ConformsTo = WsiProfiles. BasicProfile1_1)]
// To allow ASP. net ajax to call this Web service from a script, cancel the comments to the downstream.
// [System. Web. Script. Services. ScriptService]
Public class Service: System. Web. Services. WebService
{
Public Service (){
// If you use the designed component, uncomment the following line
// InitializeComponent ();
}
// [WebMethod]
// Public string HelloWorld ()
//{
// Return "Hello World ";
//}
[WebMethod (Description = "summation method")]
Public double addition (double I, double j)
{
Return I + j;
}
[WebMethod (Description = "difference calculation method")]
Public double subtract (double I, double j)
{
Return I-j;
}
[WebMethod (Description = "method for product calculation")]
Public double multiplication (double I, double j)
{
Return I * j;
}
[WebMethod (Description = "method of quotient calculation")]
Public double pision (double I, double j)
{
If (j! = 0)
Return I/j;
Else
Return 0;
}
}


Run the command to view the methods we have written that can be called, such:

Similarly, click the addition method to go to the addition method call page.

Enter the parameters I = 3 and j = 3. for example, click call to view the Web Service result returned in XML format (the result of adding I and j)

Here, we will find that webservice is not so mysterious. it is just an interface. for us, the focus is on writing interface functions.

2.3. use ASP. NET to call Web Service
First, open VS2005, open "file-new-website", and select "ASP. NET website ".

Select the storage location and click "OK" to go to the default page. Then add a Web reference to bring the WebService to the current project. The method is as follows: Right-click the resource manager and choose Add Web reference to bring up the dialog box:

Fill in the URL. enter the address displayed in the browser after the WebService is run (that is, the access address after the WebService is published), and click "Go", as shown in, the method that can be called in the referenced WebService is displayed. click "Add reference" to reference webservice to the current project, as shown in, the introduced WebService file appears in the solution.

Here we will practice calling webservice's four methods. for a simple call example, add several controls on the front-end of the website. The code is as follows:

The code is as follows:

<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default. aspx. cs" Inherits = "_ Default" %>



No title page





<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default. aspx. cs" Inherits = "_ Default" %>



No title page





Then write the calling code in the background. before calling the code, just like using other objects, instantiate the code first. The instantiation method is localhost. service a = new localhost. service (); then you can use a to access the methods provided in WebService. In this example, a button control is dynamically created to trigger WebService calls. the background code is as follows:
After running, you can see the effect, as shown in. enter two operands in the first two Textbox, select the operator from the drop-down list in the middle, and click "=, output the calculated result to the third Textbox.

However, the entire computation is not performed locally. the computation is performed on the Web server and the results are returned to the caller through XML. Therefore, when running the program, the WebService program must also be started; otherwise, an exception will be reported that the remote server cannot be connected, for example:

The background code is as follows:

The code is as follows:

Using System;
Using System. Configuration;
Using System. Data;
Using System. Linq;
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;
Using System. Xml. Linq;
Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
}
Protected void button#click (object sender, EventArgs e)
{
String selectFlag = selectOper. Value;
Localhost. Service web = new localhost. Service ();
If (selectFlag. Equals ("+ "))
{
Result. Text = (web. addition (double. Parse (Num1.Text), double. Parse (Num2.Text). ToString ();
}
Else if (selectFlag. Equals ("-"))
{
Result. Text = (web. subtract (double. Parse (Num1.Text), double. Parse (Num2.Text). ToString ();
}
Else if (selectFlag. Equals ("*"))
{
Result. Text = (web. multiplication (double. Parse (Num1.Text), double. Parse (Num2.Text). ToString ();
}
Else if (selectFlag. Equals ("/"))
{
Result. Text = (web. pision (double. Parse (Num1.Text), double. Parse (Num2.Text). ToString ();
}
}
}


The code is as follows:

Using System;
Using System. Configuration;
Using System. Data;
Using System. Linq;
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;
Using System. Xml. Linq;
Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
}
Protected void button#click (object sender, EventArgs e)
{
String selectFlag = selectOper. Value;
Localhost. Service web = new localhost. Service ();
If (selectFlag. Equals ("+ "))
{
Result. Text = (web. addition (double. Parse (Num1.Text), double. Parse (Num2.Text). ToString ();
}
Else if (selectFlag. Equals ("-"))
{
Result. Text = (web. subtract (double. Parse (Num1.Text), double. Parse (Num2.Text). ToString ();
}
Else if (selectFlag. Equals ("*"))
{
Result. Text = (web. multiplication (double. Parse (Num1.Text), double. Parse (Num2.Text). ToString ();
}
Else if (selectFlag. Equals ("/"))
{
Result. Text = (web. pision (double. Parse (Num1.Text), double. Parse (Num2.Text). ToString ();
}
}
}


By now, the development and calling of a simple WebService have been completed. in actual applications, you can write powerful and complex webservices according to your own needs. no matter how complicated, the whole process is like this.

The basic concept of movie Service Web Service is also called XML Web Service WebService. it is a lightweight and independent Service that can receive requests from other systems on the Internet or Intranet...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.