?????? 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;
@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如下:
<?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>
??
?
?
?
?
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

