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

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



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

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



Java代码
///在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());

///在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 。。。。

项目结构如下:






实现代码如下:



Java代码
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;

@Override
public 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() {
@Override
public 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) {
// 定义待请求的URL
String 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();
}
}

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;

@Override
public 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() {
@Override
public 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) {
// 定义待请求的URL
String 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如下:


Java代码
<?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>

<?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如下:






Java代码
<?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>
http://topmanopensource.iteye.com/blog/1283845

更多相关文章

  1. Android(安卓)的系统属性(SystemProperties)设置分析
  2. Android(安卓)关于获取摄像头帧数据
  3. Android(安卓)/ iOS 静态代码扫描工具调研
  4. 编译Android(安卓)使用 Java5 还是 Java6
  5. 在Android(安卓)Service中弹出系统全屏对话框
  6. Android(安卓)-- 设置textview文字居中或者控件居中
  7. 利用Handler定时更新Android(安卓)UI
  8. Android(安卓)Studio多渠道批量打包及代码混淆
  9. Android_判断文件是否存在并创建代码

随机推荐

  1. 实现在一个界面里多个TextView的跑马灯效
  2. 访问Android硬件资源の管理网络和Wifi连
  3. Android实现侧拉DrawerLayout简单用法
  4. Android提高第十九篇之"多方向"抽屉
  5. 植物大战僵尸2 Android破解版,免费买道具
  6. 打开电话Android系统调用
  7. Android电源管理
  8. [置顶] Android如何使用Https
  9. Android(安卓)属性总结
  10. Android前置摄像头预览并检测人脸,获取人