原理:通过HTTP协议发送XML数据并调用webservice(soap)
首先定义string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">手机号码归属查询</string>
<string name="mobile">手机号</string>
<string name="button">查询</string>
<string name="error">连接失败</string>
</resources>
构建一个布局:
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/mobile" />
<EditText
android:id="@+id/mobile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/button" />
<TextView
android:id="@+id/result"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
效果图:
然后编写activity:
package cn.csdnmobile;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
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;
import cn.csdn.service.MobileService;
public class MobileNumberBelongActivity extends Activity implements OnClickListener{
Button submitBtn ;
EditText numberEt;
TextView resultTv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViews();
}
private void findViews() {
numberEt = (EditText) this.findViewById(R.id.mobile);
submitBtn = (Button) this.findViewById(R.id.button);
resultTv = (TextView) this.findViewById(R.id.result);
submitBtn.setOnClickListener(this);
}
//监听,判断并得到数据
public void onClick(View v) {
String PhoneNumber = numberEt.getText().toString().trim();
if(!"".equals(PhoneNumber)){
try {
//把数据传给MobileService类中的getMobileBelong()方法
String result = MobileService.getMobileBelong(PhoneNumber);
//显示经过上面的方法处理过后的数据
resultTv.setText(result);
} catch (Exception e) {
Log.e("TAG", e.toString());
Toast.makeText(this, R.string.error, Toast.LENGTH_LONG).show();
}
}
}
}
在得到输入的数据后,要去交给传给MobileService类中的getMobileBelong()方法处理,然后再把处理好的数据返回
package cn.csdn.service;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import android.util.Xml;
import cn.csdn.utils.StreamTool;
public class MobileService {
public static String getMobileBelong(String mobile) throws Exception{
//类加载器,调用getResourceAsStream()方法作为输入流读取资源
InputStream inStream = MobileService.class.getClassLoader().getResourceAsStream("mobile_soap.xml");
//调用建立的工具类,得到数据
byte[] data = StreamTool.readInputStream(inStream);
//重新封装数据
String xml = new String(data,"UTF-8");
/**replaceAll()方法:基于规则表达式的替换
* 其中用到了正则表达式,
* "\\$mobile" :
* 正则表达式$为正则中的特殊符号须转义,即\$mobile
* 而\为字符串中的特殊符号,所以用两个反斜杠,即"\\{1}quot;
* */
String soapEntity = xml.replaceAll("\\$mobile", mobile);
data = soapEntity.getBytes();
//定义发送的目的地址
String path="http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
//建立连接
URL url = new URL(path);
// 转换 HttpURLConnection是专门为http的连接而设计的类
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//post发送,设置允许得到一个输入流
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 outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
//请求成功
if(conn.getResponseCode() == 200){
//接收数据
InputStream responseStream = conn.getInputStream();
return pareseXml(responseStream);
}
return null;
}
//xml解析器
private static String pareseXml(InputStream responseStream) throws Exception {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(responseStream, "UTF-8");
int event = parser.getEventType();
while(event != XmlPullParser.END_DOCUMENT){
switch(event){
case XmlPullParser.START_TAG:
if("getMobileCodeInfoResult".equals(parser.getName())){
return parser.nextText();
}
break;
}
event = parser.next();
}
return null;
}
}
要调用webservice(soap),所以定义mobile_soap.xml
在MobileService.java 中调用此类转换的语句:InputStream inStream = MobileService.class.getClassLoader().getResourceAsStream("mobile_soap.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>
在调用mobile_soap.xml 的时候,要把xml格式转换成字节,所以在这里要定义一个类
在MobileService.java 中调用此类转换的语句:byte[] data = StreamTool.readInputStream(inStream);
package cn.csdn.utils;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTool {
/**
* 从输入流读取数据
* 把数据封装到ByteArrayOutputStream
* 为什么要封装:可以把它轻而易举的做一个字节类型的转换
*
* 然后返回
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream)
throws Exception {
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
}
可以实现了。。。。