In some cases we may need to interact with MySQL or Oracle databases, and some friends ' first reaction is to load the driver directly into Android and then make data additions and deletions. I personally do not recommend this approach, a mobile phone is not a computer after all, the operation of a large number of data time-consuming cost electricity, and the second is that the flow of expensive such as gold. I personally recommend the practice is to use Java or PHP and other development interfaces or write WebService database additions and deletions of the check, and then Android call the interface or webservice for data interaction. This article explains how to invoke the webservice provided by the remote server in Android.
Since it is called WebService, we first build the WebService server.
The following demo is how to use the site to provide mobile phone number attribution to query WebService service query number attribution
Call Address Http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo.
First, you save the request message in an XML file, and then use the $ replacement request parameter, as follows:
Mobilesoap.xml
<span style= "FONT-SIZE:16PX;" ><?xml version= "1.0" encoding= "Utf-8"?> <soap12:envelope xmlns:xsi=
"http://www.w3.org/2001/" Xmlschema-instance "xmlns:xsd=" Http://www.w3.org/2001/XMLSchema "xmlns:soap12=" http://www.w3.org/2003/05/ Soap-envelope ">
<soap12:Body>
<getmobilecodeinfo xmlns=" http://WebXml.com.cn/">
< mobilecode> $mobile </mobileCode>
<userID></userID>
</getMobileCodeInfo>
</soap12:Body>
</soap12:Envelope></span>
Secondly, design the mainactivity layout file,
Main.xml
<span style= "FONT-SIZE:16PX;" ><?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/" Res/android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" fill_parent "> <textview android:layout_width=" fill_parent "android:layout_height=" Wrap_content "android:text= "Mobile number"/> <edittext android:id= "@+id/mobilenum" android:layout_width= "Fill_parent" android:layout _height= "Wrap_content" android:text= ""/> <button android:id= "@+id/btnsearch" Android:layout_ Width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Query"/> <textview
Oid:id= "@+id/mobileaddress" android:layout_width= "fill_parent" android:layout_height= "Wrap_content"/> </LinearLayout></span>
The mainactivity is posted below,
Calling WebService in Android is simpler: request WebService, get the service response data, parse it, and display it.
<span style= "FONT-SIZE:16PX;"
>package Com.szy.webservice;
Import Java.io.ByteArrayOutputStream;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;
Import Org.xmlpull.v1.XmlPullParser;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.Log;
Import android.util.Xml;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.TextView;
Import Android.widget.Toast; /** * @author coolszy * @date 2012-3-8 * @blog http://blog.92coding.com/public class Mainactivity extends
vity {private EditText mobilenum;
Private TextView mobileaddress;
private static final String TAG = "mainactivity"; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savEdinstancestate);
Setcontentview (R.layout.main);
Mobilenum = (edittext) This.findviewbyid (r.id.mobilenum);
Mobileaddress = (TextView) This.findviewbyid (r.id.mobileaddress);
Button btnsearch = (button) This.findviewbyid (R.id.btnsearch);
Btnsearch.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v)
{//Get phone number String mobile = Mobilenum.gettext (). toString ();
Read XML file InputStream instream = This.getclass (). getClassLoader (). getResourceAsStream ("Mobilesoap.xml"); try {//show the location of the phone number, which is unreasonable, for reference only Mobileaddress.settext (Getmobileaddress instream, mobile
));
catch (Exception e) {log.e (TAG, e.tostring ());
Toast.maketext (mainactivity.this, "Query failed", 1). Show ();
}
}
}); /** * Get Phone number location * * @param instream * @param mobile * @return * @throwS Exception */private string getmobileaddress (InputStream instream, String mobile) throws Exception {//
Change the phone number in the XML file String soap = Readsoapfile (instream, mobile);
byte[] data = Soap.getbytes ();
Submit POST request URL url = new URL ("Http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Conn.setrequestmethod ("POST");
Conn.setconnecttimeout (5 * 1000);
Conn.setdooutput (TRUE); Conn.setrequestproperty ("Content-type", "application/soap+xml;
Charset=utf-8 ");
Conn.setrequestproperty ("Content-length", String.valueof (Data.length));
OutputStream OutStream = Conn.getoutputstream ();
Outstream.write (data);
Outstream.flush ();
Outstream.close ();
if (conn.getresponsecode () = = 200) {//Parse return information returned Parseresponsexml (Conn.getinputstream ());
return "Error"; Private String readsoapfile (InputStream inStrEAM, String Mobile) throws Exception {//Get file information from stream byte[] data = Readinputstream (instream);
String soapxml = new string (data);
Placeholder parameter map<string, string> params = new hashmap<string, string> ();
Params.put ("mobile", mobile);
Replace placeholder return replace (soapxml, params) in a file; /** * Read Stream information * * @param inputstream * @return * @throws Exception * * Private byte[] Rea
Dinputstream (InputStream inputstream) throws Exception {byte[] buffer = new byte[1024];
int len =-1;
Bytearrayoutputstream Outsteam = new Bytearrayoutputstream ();
while (len = inputstream.read (buffer))!=-1) {outsteam.write (buffer, 0, Len);
} outsteam.close ();
Inputstream.close ();
return Outsteam.tobytearray (); /** * Replace placeholder in file * @param XML * @param params * @return * @throws Exception/pri Vate string Replace (string xml, Map<string, STRIng> params) throws Exception {String result = XML; if (params!= null &&!params.isempty ()) {for (map.entry<string, string> entry:params.entrySe
T ()) {String name = ' \\$ ' + entry.getkey ();
Pattern pattern = pattern.compile (name);
Matcher Matcher = Pattern.matcher (result);
if (Matcher.find ()) {result = Matcher.replaceall (Entry.getvalue ());
}} return result; /** * Parse XML file * @param instream * @return * @throws Exception * * private static String par
Seresponsexml (InputStream instream) throws Exception {Xmlpullparser parser = Xml.newpullparser ();
Parser.setinput (instream, "UTF-8"); int eventtype = Parser.geteventtype ()//generates first event while (EventType!= xmlpullparser.end_document) {//Only is the document End Event switch (eventtype) {case XmlPullParser.START_TAG:String name= Parser.getname ()//Get the name of the element that the parser is currently pointing to if ("Getmobilecodeinforesult". Equals (name)) {return PA
Rser.nexttext ();
} break;
} EventType = Parser.next ();
return null;
}}</span>
Finally, because you need access to the network, you need to add permissions
<span style= "FONT-SIZE:16PX;" ><uses-permission android:name= "Android.permission.INTERNET"/></span>
With the simple example above, I'm sure you've learned how to invoke WebService in Android and finally run the effect:
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.