Android开发入门之发送XML数据和调用webservice

来源:互联网 发布:网络女征婚骗局案例 编辑:程序博客网 时间:2024/06/01 18:12

新建一个项目mobileAddressQuery,添加测试所需要的配置以及访问网络权限

将person.xml放到src目录下:

<?xml version="1.0" encoding="UTF-8"?><persons>    <person id="23">        <name>gaolei</name>        <age>23</age>    </person>    <person id="24">        <name>xiaoqiang</name>        <age>25</age>    </person></persons>

XmlTest.java:

package cn.leigo.test;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import cn.leigo.utils.StreamTool;import android.test.AndroidTestCase;import android.util.Log;public class XmlTest extends AndroidTestCase {private static final String TAG = "XmlTest";public void testSendXML() throws Exception {InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("person.xml");byte[] data = StreamTool.read(inputStream);String path = "http://192.168.1.100:8080/videonews/XmlServlet";URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("POST");conn.setDoOutput(true);conn.setRequestProperty("Content-Type", "text/html; charset=UTF-8");conn.setRequestProperty("Content-Length", String.valueOf(data.length));conn.getOutputStream().write(data);if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {Log.d(TAG, "发送成功!");} else {Log.d(TAG, "发送失败!");}}}

StreamTool.java

package cn.leigo.utils;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;public class StreamTool {/** * 读取流中的数据 *  * @param inputStream * @return * @throws IOException */public static byte[] read(InputStream inputStream) throws IOException {ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inputStream.read(buffer)) != -1) {baos.write(buffer, 0, len);}inputStream.close();return baos.toByteArray();}}

服务器端:

package cn.leigo.servlet;import java.io.IOException;import java.io.InputStream;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import cn.leigo.utils.StreamTool;public class XmlServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {InputStream inputStream = request.getInputStream();byte[] data = StreamTool.read(inputStream);String xml = new String(data, "UTF-8");System.out.println(xml);}}




打开http://www.webxml.com.cn/zh_cn/index.aspx,里面有很多供你调用的API,我们打开手机归属地查询http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx

以下是 SOAP 1.2 请求和响应示例。所显示的占位符需替换为实际值。

POST /WebServices/MobileCodeWS.asmx HTTP/1.1Host: webservice.webxml.com.cnContent-Type: application/soap+xml; charset=utf-8Content-Length: length<?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>string</mobileCode>      <userID>string</userID>    </getMobileCodeInfo>  </soap12:Body></soap12:Envelope>

HTTP/1.1 200 OKContent-Type: application/soap+xml; charset=utf-8Content-Length: length<?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>

第一步:新建一个Android工程命名为mobileAddressQuery目录结构如下图:


第二步:修改activity_main.xml布局文件代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/mobile" />    <EditText        android:id="@+id/et_mobile"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:inputType="phone" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="query"        android:text="@string/query" />    <TextView        android:id="@+id/tv_address"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center" /></LinearLayout>

strings.xml:

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="app_name">手机号归属地查询</string>    <string name="action_settings">Settings</string>    <string name="hello_world">Hello world!</string>    <string name="mobile">手机号码</string>    <string name="query">查询</string>    <string name="please_enter_mobile_number">请输入手机号码,最少前7位数字</string>    <string name="success">查询成功!</string>    <string name="fail">查询失败!</string>    <string name="error">查询出错!</string></resources>

第三步:建立web服务的xml ----->soap12.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>

第四步:编写MianActivity类:

package cn.leigo.address;import android.app.Activity;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import cn.leigo.service.AddressService;public class MainActivity extends Activity {private EditText mMobileEditText;private TextView mAddressTextView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mMobileEditText = (EditText) findViewById(R.id.et_mobile);mAddressTextView = (TextView) findViewById(R.id.tv_address);}public void query(View v) {String mobile = mMobileEditText.getText().toString();if (!TextUtils.isEmpty(mobile)) {try {String address = AddressService.query(mobile);mAddressTextView.setText(address);Toast.makeText(this, R.string.success, Toast.LENGTH_SHORT).show();} catch (Exception e) {e.printStackTrace();Toast.makeText(this, R.string.fail, Toast.LENGTH_SHORT).show();}} else {Toast.makeText(this, R.string.please_enter_mobile_number,Toast.LENGTH_SHORT).show();}}}

业务类AddressService.java:

package cn.leigo.service;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserException;import android.util.Xml;import cn.leigo.utils.StreamTool;public class AddressService {/** * 获取手机归属地 *  * POST /WebServices/MobileCodeWS.asmx HTTP/1.1 Host: * webservice.webxml.com.cn Content-Type: application/soap+xml; * charset=utf-8 Content-Length: length *  * <?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>string</mobileCode> <userID>string</userID> * </getMobileCodeInfo> </soap12:Body> </soap12:Envelope> *  * @param mobile * @return * @throws IOException * @throws XmlPullParserException */public static String query(String mobile) throws IOException,XmlPullParserException {String soap = readSoap();String soapEntity = soap.replaceAll("\\$mobile", mobile);byte[] data = soapEntity.getBytes();String path = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setDoOutput(true);conn.setConnectTimeout(5000);conn.setRequestMethod("POST");conn.setRequestProperty("Content-Type","application/soap+xml;charset=utf-8");conn.setRequestProperty("Content-Length", String.valueOf(data.length));OutputStream outputStream = conn.getOutputStream();outputStream.write(data);outputStream.flush();outputStream.close();if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {return parseSOAP(conn.getInputStream());}return null;}/** * HTTP/1.1 200 OK Content-Type: application/soap+xml; charset=utf-8 * Content-Length: length *  * <?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 inputStream)throws XmlPullParserException, IOException {XmlPullParser parser = Xml.newPullParser();parser.setInput(inputStream, "UTF-8");int eventType = parser.getEventType();while (eventType != XmlPullParser.END_DOCUMENT) {switch (eventType) {case XmlPullParser.START_TAG:if ("getMobileCodeInfoResult".equals(parser.getName())) {return parser.nextText();}break;}eventType = parser.next();}return null;}private static String readSoap() throws IOException {InputStream inputStream = AddressService.class.getClassLoader().getResourceAsStream("soap12.xml");byte[] data = StreamTool.read(inputStream);return new String(data, "UTF-8");}}

工具类StreamTool:

package cn.leigo.utils;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;public class StreamTool {/** * 读取流中的数据 *  * @param inputStream * @return * @throws IOException */public static byte[] read(InputStream inputStream) throws IOException {ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inputStream.read(buffer)) != -1) {baos.write(buffer, 0, len);}inputStream.close();return baos.toByteArray();}}

最后别忘了在AndroidManifest.xml文件中添加权限:

<uses-permission android:name="android.permission.INTERNET" />

运行上述工程查看效果图:


原创粉丝点击