Develop a Chinese-English Translation software (3) Web Service based on Web Service in the Android Project

Source: Internet
Author: User

About Web Service

Android applications usually run on mobile platforms. The hardware resources of mobile systems are far inferior to those of PC platforms. Whether it is storage or computing, it is possible to run some small applications on Android platforms, however, for a large amount of data processing, complex computing can only be deployed on remote servers, while Android applications can only act as clients for these applications. This Chinese-English Translation software, in fact, it is the client access window deployed on the server for the Sino-English Translation Service. Users can access the server through the client. complex data processing and massive data storage are on the server. The client is only responsible for presenting the data prepared by the server to the user, therefore, it does not undertake a lot of data operations. In order to realize the function of remote access to the Service, Web Service is a good choice.

For example, if my company provides a translation service, I want other companies to use this service and allow other companies to develop their own translation software, then, I can use CXF to develop a Web Servie and put it on our server, and publish its corresponding WSDL document for external use.

  What Is a wsdl document?

This is very important. It is the language used to describe Web services. For example, if you want someone to use your Web product, you cannot tell people how to use it. You need to provide a manual, the WSDL is the Web Service Specification. I want to use a Chinese-English Translation Web Service. The WSDL provided by the WSDL is also a description of the Service and can be used as an API document.

Because the focus of our development is on how to call Web services, we don't need to care about how to use CXF to develop Web services, as well as the role and significance of each element in the Web Service documentation, it is a technology developed by the Web Service server.

However, the description WSDL still needs to be read. It does not matter if it is not read. Generally, the Web Service will have instruction documents, while reading the documents, while reading the WSDL, you can explore the rules and understand the functions of those elements.

  Development

First, I would like to share with you a website (good thing is to take it out D), which includes a lot of free Web Services, for example, the legendary weather forecast, mobile phone number, IP address, train schedule, email verification, verification code image generation, and what stock are there? Is it fun to listen? The connection is as follows (I am not advertising, but now many Andoird textbooks use this website ):

Http://www.webxml.com.cn/zh_cn/index.aspx

  Is it possible to call Web Service on the Android platform with WSDL??

Not enough! We also need a jar package, ksaop2-android.

Goolge for Android platform development Web Service client provides a ksoap2-android project, but it is not directly integrated in the Android platform, you need to download.

I will try uploading one later for your learning.

After downloading the ksoap2-android, you can use ksoap-android to call the operation exposed by Web Service, you can develop the project, of course, you must first import this package into the project.

First, let's look at the code in the previous section. Let's look at the implementation steps behind me and then compare them with the code.

  

 

 1 package wuchen.utils; 2  3 import java.util.ArrayList; 4 import java.util.List; 5  6 import org.ksoap2.SoapEnvelope; 7 import org.ksoap2.serialization.SoapObject; 8 import org.ksoap2.serialization.SoapSerializationEnvelope; 9 import org.ksoap2.transport.HttpTransportSE;10 11 public class Ksoap2 {12     13     private static final String SERVICE_URL = "http://fy.webxml.com.cn/webservices/EnglishChinese.asmx";14     private static final String SERVICE_NS = "http://WebXml.com.cn/";15     private static final String WORD_KEY = "wordKey";16     private List<String> messageList;17     18     public List<String> getMessgesList(String methodName,String words) throws Exception {19         return getSoapObject(methodName,words);20     }21         22     private List<String> getSoapObject(String methodName,String words) throws Exception{23         HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);24         ht.debug = true;25         SoapSerializationEnvelope envelope = 26                 new SoapSerializationEnvelope(SoapEnvelope.VER11);27         SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);28         soapObject.addProperty(WORD_KEY,words);29         envelope.bodyOut = soapObject;30         envelope.dotNet = true;31         32             ht.call(SERVICE_NS + methodName, envelope);33             if(envelope.getResponse() != null){34                 SoapObject so = (SoapObject)envelope.bodyIn;35                 List<String> messageList = getTransMessage(so, 0, methodName + "Result");36                 return messageList;37             }38             39     40         return null;41     }42     43     private List<String> getTransMessage(SoapObject so, int index, String name_value){44         45         SoapObject detail;46         if(name_value != null && !"".equals(name_value)){47             detail = (SoapObject)so.getProperty(name_value);48         }else{49             detail = (SoapObject)so.getProperty(index);50         }51         return parseTransMessage(detail);52     }53     private List<String> parseTransMessage(SoapObject detail) {54         // TODO Auto-generated method stub55         messageList = new ArrayList<String>();56         for(int i = 0; i < detail.getPropertyCount(); i++){57             messageList.add(detail.getProperty(i).toString());58         }59         return messageList;60     }61 }

 

 

This code is the core code for calling Web Service in my project;

To call a Web Service using ksoap2, follow these steps:

1. Create an HttpTransportSE object (Conveyor Belt) to call Web Service. See 23 lines of code.

2. Create a SoapSerializationEnvelope object (an envelope containing SOAP information). For details, see line 25 of the Code.

3. Create a SoapObject object. When creating this object, you need to input the namespace of the WebService to be called. How do you know the namespace of the called Web Service? Open the URL mentioned above and find the Web Service you are interested in. I am a Chinese-English translator.

  

  

You can see the link address of the WSDL file (if you are interested in the two above, you can open it by yourself). As mentioned above, this file is the description of Web Service, that is, commit, the namespace of this service will also be described in it. Let's open it.

  

Place where you want to stick with a yellow stroke: targetNamespace = "WebXml.com.cn", where WebXml.com.cn is the namespace of this Service. When creating a SoapObject object, just upload it to it, the second parameter for creating a SoapObject is described later. See 27 lines of code.

4. If a parameter needs to be passed to the Web Service server, call the addProperty (String key, Object value) method of the SoapObject Object. Here I will pass in the data of words or phrases to be translated. See 28 lines of code.

5. Call the setOutputSoapObject () method of the SoapSerializationEnvelope object created earlier, or directly assign a value to the bodyOut attribute to set the SoapObject created earlier to the outgoing SOPA of SoapSerializationEnvelope. Here I use the direct assignment of the bodyOut attribute, as shown in line 29 of the Code.

6. call the call () method of the HttpTransportSE object and use SopaSerializationEnvlope as the parameter to call the remote Web Service. See the code: 32 lines.

7. After the call is complete, access the bodyIn of the SoapSerializationEnvelope object. This attribute returns a SopaObjec object, which represents the data returned by a Web Service server, parse the SoapObject to get the data you want. For details, see 35 lines of code. I encapsulated the data parsing.

The above seven steps roughly explain how to call the Web Service with ksoap2, but I will explain it in detail below. The first step is to create an HttpTransportSE object that requires a SERVICE_URL parameter. How can I obtain this parameter? When you open the WSDL connection, the address displayed in the address bar of the browser is the SERVICE_URL of the service. See the figure below:

Note that I want to remove the place where I stick with yellow strokes,See 13 lines of code.

Because the method in my core code is called externally, I have not mentioned the methodName parameter. What does this parameter mean? To put it bluntly, you can see through the WSDL document that the Web Service exposes those functions to the caller. We only need to set the name (methodName) of the function you want to use in the call () method) the corresponding data can be returned after being passed to the Web Service. For details, see line 27 of the code used to create a SoapObject object and used to execute the call () method. The difference is that, add the prefix namespace here, as shown in Row 32.

How do we know the methods that Web Service provides for callers? What are the return values of these methods? What are the names of these methods? What is the role?We still need the WSDL document to help you answer the above questions. As I mentioned above, since I have not read the WSDL, I do not understand what is written in it, and it does not matter, because most Web Services provide descriptive example documents for users. As the example document of this application is also shown in the above texture, we can open it to see the following content:

  

This document is only partial. First, check the first line of the red letter. This line is the method name exposed by Web Service. Then, the returned value is a String []. the length of the array has been determined to be 5. That is to say, when creating a SoapObject, we will pass in the method name "TranslatorString". After calling the call () method, then, the SoapObject object carrying data is obtained from the bodyIn attribute of the SoapSerializationEnvelope object, and then the SoapObject object obtains a SoapObject object through its own getProperty ("TranslatorString" + "Result") method, after reading the document, we know that the TranslatorString method returns a fixed-length String []. We also know the content of each element corresponding to each badge, therefore, we can call the getProperty (1) method of the final SoapObject object to obtain the phonetic alphabet or Pinyin of the words to be translated. GetProperty (4) Get the Mp3 name for reading English words ......, Here, I directly put the data into the List for use after a for loop, as shown in line 53 of the Code.

You can call the Web Service in the above seven steps and obtain the information you want. However, it looks really messy and can be understood in this way. The HttpTransportSE (trans) object can be regarded as a conveyor belt. The SoapSerializationEnvelope object (envelope) is a postman and SoapObject (so) is a package:

So. addProperty (WordKey, word): load the "inquired" information into the package.

Envlope. bodyOut = so: the postman takes the Out package and is waiting for delivery.

Ht. call (..., envlope) method: the postman takes the package and jumps onto the conveyor belt to access the server and exchange data.

SoapObject so = (SoapObject) envlope. bodyIn: take out the package exchanged with the server from the postman. This package is not the same as the so object above.

So. getProperty (...): extracts the "Answer" information from the package.

The above is the way to call Web Service with a ksoap2-android.

  

Next article: coexistence of Sqlite and Web Service

 

From: One Kid Sky

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.