Android通过Apache HttpClient调用网上提供的WebService服务,获取电话号码所属的区域。调用的服务的网址:

http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo

以前用2.2 访问WebService没有问题,到3.0上访问出现android.os.NetworkOnMainThreadException

找了资料经过实践,解决方法如下:

///在Android2.2以后必须添加以下代码//本应用采用的Android4.0//设置线程的策略 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()            .detectDiskReads()            .detectDiskWrites()            .detectNetwork()   // or .detectAll() for all detectable problems            .penaltyLog()            .build());   //设置虚拟机的策略  StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()            .detectLeakedSqlLiteObjects()            .detectLeakedClosableObjects()            .penaltyLog()            .penaltyDeath()            .build());

 
 

似乎是3.0在网络上做了更加严格的限制,更多的查询API上的StrictMode 。。。。

项目结构如下:

运行结果如下:

实现代码如下:

package com.easyway.android.query.telephone;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import android.app.Activity;import android.os.Bundle;import android.os.StrictMode;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;/** * 利用网上提供的WebService使用 * HttpClient运用之手机号码归属地查询 * 参看WebService地址: *    http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo *     *    可以采用 *      SOAP1.1,SOAP1.2,HTTP GET,HTTP POST *  * @author longggangbai *  */public class AndroidQueryTelCodeActivity extends Activity {private EditText phoneSecEditText;private TextView resultView;private Button queryButton;@Overridepublic void onCreate(Bundle savedInstanceState) {///在Android2.2以后必须添加以下代码//本应用采用的Android4.0//设置线程的策略 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()            .detectDiskReads()            .detectDiskWrites()            .detectNetwork()   // or .detectAll() for all detectable problems            .penaltyLog()            .build());   //设置虚拟机的策略  StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()            .detectLeakedSqlLiteObjects()            .detectLeakedClosableObjects()            .penaltyLog()            .penaltyDeath()            .build());super.onCreate(savedInstanceState);//设置界面布局setContentView(R.layout.main);//初始化界面        initView();        //设置各种监听setListener();}/** * 界面相关的各种设置 */private void initView() {//手机号码编辑器phoneSecEditText = (EditText) findViewById(R.id.phone_sec);//resultView = (TextView) findViewById(R.id.result_text);queryButton = (Button) findViewById(R.id.query_btn);}    /**     * 设置各种事件监听的方法     */private void setListener() {queryButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 手机号码(段)String phoneSec = phoneSecEditText.getText().toString().trim();// 简单判断用户输入的手机号码(段)是否合法if ("".equals(phoneSec) || phoneSec.length() < 7) {// 给出错误提示phoneSecEditText.setError("您输入的手机号码(段)有误!");//获取焦点phoneSecEditText.requestFocus();// 将显示查询结果的TextView清空resultView.setText("");return;}// 查询手机号码(段)信息getRemoteInfo(phoneSec);}});}/** * 手机号段归属地查询 *  * @param phoneSec *            手机号段 */public void getRemoteInfo(String phoneSec) {// 定义待请求的URLString requestUrl = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";// 创建HttpClient实例HttpClient client = new DefaultHttpClient();// 根据URL创建HttpPost实例HttpPost post = new HttpPost(requestUrl);List<NameValuePair> params = new ArrayList<NameValuePair>();// 设置需要传递的参数params.add(new BasicNameValuePair("mobileCode", phoneSec));params.add(new BasicNameValuePair("userId", ""));try {// 设置URL编码post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));// 发送请求并获取反馈HttpResponse response = client.execute(post);// 判断请求是否成功处理if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 解析返回的内容String result = EntityUtils.toString(response.getEntity());// 将查询结果经过解析后显示在TextView中resultView.setText(filterHtml(result));}} catch (Exception e) {e.printStackTrace();}}/** * 使用正则表达式过滤HTML标记 *  * @param source *            待过滤内容 * @return */private String filterHtml(String source) {if (null == source) {return "";}return source.replaceAll("</?[^>]+>", "").trim();}}

界面代码main.xml如下:

<?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"      android:paddingTop="5dip"      android:paddingLeft="5dip"      android:paddingRight="5dip"      >      <TextView          android:layout_width="fill_parent"           android:layout_height="wrap_content"           android:text="手机号码(段):"      />      <EditText android:id="@+id/phone_sec"          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:inputType="textPhonetic"          android:singleLine="true"          android:hint="例如:1398547(手机号码前8位)"      />      <Button android:id="@+id/query_btn"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_gravity="right"          android:text="查询"      />      <TextView android:id="@+id/result_text"          android:layout_width="wrap_content"           android:layout_height="wrap_content"           android:layout_gravity="center_horizontal|center_vertical"      />  </LinearLayout>  

全局文件AndroidManifest.xml如下:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.easyway.android.query.telephone"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="14" />    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <activity            android:label="@string/app_name"            android:name=".AndroidQueryTelCodeActivity" >            <intent-filter >                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>    <uses-permission android:name="android.permission.INTERNET" />  </manifest>

更多相关文章

  1. Android(安卓)权限表
  2. android 补间动画TranslateAnimation
  3. 转:bitmap设置图片尺寸缩小,避免内存溢出/OutOfMemoryError的优化
  4. Android(安卓)SimpleAdapter 的list刷新问题。
  5. Android(安卓)返回上一个界面刷新数据
  6. bitmap设置图片尺寸缩小,避免内存溢出/OutOfMemoryError的优化方
  7. Building System之编译前的准备工作
  8. Android(安卓)EditText设置Filter以后,xml布局文件中maxLength不
  9. Android下的配置管理之道之gerrit权限管理

随机推荐

  1. android高效编程之使用本地变量
  2. 【Android】OpenGL ES for Android 教程1
  3. 看Android 應用框架原理與程式設計36 技有
  4. Android AIDL 实例
  5. Android 图片预览模仿朋友圈查看图片效果
  6. mac电脑开发android找不到设备
  7. android TraceView (图形化性能测试工具)
  8. Android Bundle传递对象
  9. Mac配置Android环境 adb
  10. Android 关机、重启、recovery流程分析