简介
Web Service
1.例子:使用WebService电话号码归属地查询
http://www.webxml.com.cn/zh_cn/index.aspx 网站有电话号码归属地查询
WebService API ,只需要在实现这API就可以了
(1)界面配置文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/phone" /> <EditText android:id="@+id/phonenum" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="phone" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/search" /> <TextView android:id="@+id/result" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
(2)AndroidInteractWithWebService.xml
<?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>
(3)StreamTool.java
package com.webservice.tool; import java.io.ByteArrayOutputStream; import java.io.InputStream; public class StreamTool { /** * 从流中读取数据 * * @param inStream * @return */ public static byte[] read(InputStream inStream) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outputStream.write(buffer,len); } inStream.close(); return outputStream.toByteArray(); } }
5)WebServiceRequestFromAndroid
package com.webservice.service; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.xmlpull.v1.XmlPullParser; import com.webservice.tool.StreamTool; import android.util.Xml; public class WebServiceRequestFromAndroid { /** * 获取手机号归属地 * * @param mobile * 手机号 * @return * @throws Exception */ public static String getAddress(String mobile) throws Exception { String soap = readSoap(); soap = soap.replaceAll("\\$mobile",mobile); byte[] entity = soap.getBytes(); String path = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx"; HttpURLConnection conn = (HttpURLConnection) new URL(path) .openConnection(); conn.setConnectTimeout(50000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8"); conn.setRequestProperty("Content-Length",String.valueOf(entity.length)); conn.getoutputStream().write(entity); if (conn.getResponseCode() == 200) { return parseSOAP(conn.getInputStream()); } return null; } /* * <?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> * <getMobileCodeInfoResponse xmlns="http://WebXml.com.cn/"> * <getMobileCodeInfoResult>string</getMobileCodeInfoResult> * </getMobileCodeInfoResponse> </soap12:Body> </soap12:Envelope> */ private static String parseSOAP(InputStream xml) throws Exception { XmlPullParser pullParser = Xml.newPullParser(); pullParser.setInput(xml,"UTF-8"); int event = pullParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { switch (event) { case XmlPullParser.START_TAG: if ("getMobileCodeInfoResult".equals(pullParser.getName())) { return pullParser.nextText(); } break; } event = pullParser.next(); } return null; } private static String readSoap() throws Exception { InputStream inStream = WebServiceRequestFromAndroid.class .getClassLoader().getResourceAsstream( "AndroidInteractWithWebService.xml"); byte[] data = StreamTool.read(inStream); return new String(data); } }
(6)MainActivity.java
package com.example.webservice; import com.webservice.service.WebServiceRequestFromAndroid; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private Button button = null; private EditText phone = null; private static TextView resultText = null; private final int SUCCESS = 1; private final int ERROR = 1; private String result; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == SUCCESS) { String r = (String) msg.obj; resultText.setText(r); } else if (msg.what == ERROR) { Toast.makeText(MainActivity.this,"服务器繁忙",2).show(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); phone = (EditText) findViewById(R.id.phonenum); resultText = (TextView) findViewById(R.id.result); button.setonClickListener(new OnClickListener() { @Override public void onClick(View v) { final String phoneNum = phone.getText().toString(); if (!phoneNum.equals("")) { new Thread() { public void run() { try { result = WebServiceRequestFromAndroid .getAddress(phoneNum); Message msg = new Message(); msg.what = SUCCESS; msg.obj = result; handler.sendMessage(msg); } catch (Exception e) { Message msg = new Message(); msg.what = ERROR; handler.sendMessage(msg); } } }.start(); } else { Toast.makeText(MainActivity.this,"请输入手机号",2).show(); } } }); } }
2.天气查询
(1)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/address" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <EditText android:id="@+id/phonenum" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="200" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/search" /> </LinearLayout> <ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/result" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </ScrollView> </LinearLayout>
(2)AndroidInteractWithWebService.xml
<?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> <getWeather xmlns="http://WebXml.com.cn/"> <theCityCode>$city</theCityCode> <theUserID></theUserID> </getWeather> </soap12:Body> </soap12:Envelope>
(3)StreamTool.java
package com.webservice.tool; import java.io.ByteArrayOutputStream; import java.io.InputStream; public class StreamTool { /** * 从流中读取数据 * * @param inStream * @return */ public static byte[] read(InputStream inStream) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outputStream.write(buffer,len); } inStream.close(); return outputStream.toByteArray(); } }
(4).java
package com.webservice.service; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import com.webservice.tool.StreamTool; import android.util.Xml; import android.widget.AbsoluteLayout; public class WebServiceRequestFromAndroid { /** * 获取手机号归属地 * * @param mobile * 手机号 * @return * @throws Exception */ public static String getAddress(String city) throws Exception { String soap = readSoap(); soap = soap.replaceAll("\\$city",city); byte[] entity = soap.getBytes(); String path = "http://webservice.webxml.com.cn//WebServices/WeatherWS.asmx"; HttpURLConnection conn = (HttpURLConnection) new URL(path) .openConnection(); conn.setConnectTimeout(50000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type",String.valueOf(entity.length)); conn.getoutputStream().write(entity); if (conn.getResponseCode() == 200) { String result = parseSOAP(conn.getInputStream()); String weather = result.replace("1.gif",""); return weather; } return null; } private static String parseSOAP(InputStream xml) throws Exception { String result = ""; XmlPullParser pullParser = Xml.newPullParser(); pullParser.setInput(xml,"UTF-8"); int event = pullParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { switch (event) { case XmlPullParser.START_TAG: if ("string".equals(pullParser.getName())) { result += pullParser.nextText() + "\n"; } break; } event = pullParser.next(); } return result; } private static String readSoap() throws Exception { InputStream inStream = WebServiceRequestFromAndroid.class .getClassLoader().getResourceAsstream( "AndroidInteractWithWebService.xml"); byte[] data = StreamTool.read(inStream); return new String(data); } }
(5)MainActivity.java
package com.example.webservice; import com.webservice.service.WebServiceRequestFromAndroid; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private Button button = null; private EditText phone = null; private static TextView resultText = null; private final int SUCCESS = 1; private final int ERROR = 1; private String result; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == SUCCESS) { String r = (String) msg.obj; resultText.setText(r); } else if (msg.what == ERROR) { Toast.makeText(MainActivity.this,2).show(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); phone = (EditText) findViewById(R.id.phonenum); resultText = (TextView) findViewById(R.id.result); phone.setText("清远"); button.setonClickListener(new OnClickListener() { @Override public void onClick(View v) { final String phoneNum = phone.getText().toString(); if (!phoneNum.equals("")) { new Thread() { public void run() { try { result = WebServiceRequestFromAndroid .getAddress(phoneNum); Message msg = new Message(); msg.what = SUCCESS; msg.obj = result; handler.sendMessage(msg); } catch (Exception e) { Message msg = new Message(); msg.what = ERROR; handler.sendMessage(msg); } } }.start(); } else { Toast.makeText(MainActivity.this,"请输入城市",2).show(); } } }); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。