Android 使用HTTPClient调用Web请求(查询手机号码区域)

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

项目结构如下:


Android 使用HTTPClient调用Web请求(查询手机号码区域)


Android 使用HTTPClient调用Web请求(查询手机号码区域)
实现代码如下:



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

你可能感兴趣的:(android)