Android手機歸屬地查詢工具

來源:互聯網
上載者:User

在Android應用中,我們經常會與網路上的服務端的程式(J2EE或者.NET等應用)進行互動,通訊。

本執行個體將向大家詳細介紹,在android中如何調用伺服器端提供的webservice,實現典型的分布式應用。

package cn.itcast.mobile.address;import java.io.InputStream;import cn.itcast.service.MobileInfoService;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {    private EditText mobileText;    private TextView addressView;    private static final String TAG = "MainActivity";        @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                mobileText = (EditText)this.findViewById(R.id.mobile);        addressView = (TextView)this.findViewById(R.id.address);        Button button = (Button)this.findViewById(R.id.button);        button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String mobile = mobileText.getText().toString();InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("mobilesoap.xml");try {addressView.setText(MobileInfoService.getMobileAddress(inStream, mobile));} catch (Exception e) {Log.e(TAG, e.toString());Toast.makeText(MainActivity.this, "查詢失敗", 1).show();}}});    }}

介面檔案:

<?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="@string/mobile"    />        <EditText     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:id="@+id/mobile"    />        <Button     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="@string/button"    android:id="@+id/button"    />        <TextView      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:id="@+id/address"    /></LinearLayout>

重點實現代碼:

package cn.itcast.service;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.util.Xml;import cn.itcast.utils.StreamTool;public class MobileInfoService {private static String readSoapFile(InputStream inStream, String mobile) throws Exception{byte[] data = StreamTool.readInputStream(inStream);String soapxml = new String(data);Map<String, String> params = new HashMap<String, String>();params.put("mobile", mobile);return replace(soapxml, params);}public static 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.entrySet()){String name = "\\{1}quot;+ entry.getKey();Pattern pattern = Pattern.compile(name);Matcher matcher = pattern.matcher(result);if(matcher.find()){result = matcher.replaceAll(entry.getValue());}}}return result;}public static String getMobileAddress(InputStream inStream, String mobile)throws Exception{String soap = readSoapFile(inStream, mobile);byte[] data = soap.getBytes();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);//如果通過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){return parseResponseXML(conn.getInputStream());}return null;}private static String parseResponseXML(InputStream inStream) throws Exception{XmlPullParser parser = Xml.newPullParser();parser.setInput(inStream, "UTF-8");int eventType = parser.getEventType();//產生第一個事件while(eventType!=XmlPullParser.END_DOCUMENT){//只要不是文檔結束事件switch (eventType) {case XmlPullParser.START_TAG:String name = parser.getName();//擷取解析器當前指向的元素的名稱if("getMobileCodeInfoResult".equals(name)){return parser.nextText();}break;}eventType = parser.next();}return null;}}

最後提醒大家一句,記得在項目資訊清單檔中,加入網路存取權限。

  <!-- 訪問網路的許可權 -->
<uses-permission android:name="android.permission.INTERNET"/>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.