Android(安卓)使用HTTPClient调用Web请求(查询手机号码区域)
16lz
2021-01-26
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>
更多相关文章
- Android(安卓)权限表
- android 补间动画TranslateAnimation
- 转:bitmap设置图片尺寸缩小,避免内存溢出/OutOfMemoryError的优化
- Android(安卓)SimpleAdapter 的list刷新问题。
- Android(安卓)返回上一个界面刷新数据
- bitmap设置图片尺寸缩小,避免内存溢出/OutOfMemoryError的优化方
- Building System之编译前的准备工作
- Android(安卓)EditText设置Filter以后,xml布局文件中maxLength不
- Android下的配置管理之道之gerrit权限管理