日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Android 使用HTTPClient調(diào)用Web請求(查詢手機

系統(tǒng) 2475 0

?????? Android通過Apache HttpClient調(diào)用網(wǎng)上提供的WebService服務(wù),獲取電話號碼所屬的區(qū)域。調(diào)用的服務(wù)的網(wǎng)址:

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

??????

?????? 以前用2.2 訪問WebService沒有問題,到3.0上訪問出現(xiàn) android.os.NetworkOnMainThreadException

找了資料經(jīng)過實踐,解決方法如下:

?????

    ///在Android2.2以后必須添加以下代碼
		//本應(yīng)用采用的Android4.0
		//設(shè)置線程的策略
		 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()   
         .detectDiskReads()   
         .detectDiskWrites()   
         .detectNetwork()   // or .detectAll() for all detectable problems   
         .penaltyLog()   
         .build());   
		//設(shè)置虛擬機的策略
		  StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()   
		         .detectLeakedSqlLiteObjects()   
		         .detectLeakedClosableObjects()   
		         .penaltyLog()   
		         .penaltyDeath()   
		         .build());
  

?

?

  
  

?

似乎是3.0在網(wǎng)絡(luò)上做了更加嚴(yán)格的限制,更多的查詢API上的 StrictMode 。。。。

項目結(jié)構(gòu)如下:

Android 使用HTTPClient調(diào)用Web請求(查詢手機號碼區(qū)域)

運行結(jié)果如下:

?

? Android 使用HTTPClient調(diào)用Web請求(查詢手機號碼區(qū)域)

?

實現(xiàn)代碼如下:

?

    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;

/**
 * 利用網(wǎng)上提供的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以后必須添加以下代碼
		//本應(yīng)用采用的Android4.0
		//設(shè)置線程的策略
		 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()   
         .detectDiskReads()   
         .detectDiskWrites()   
         .detectNetwork()   // or .detectAll() for all detectable problems   
         .penaltyLog()   
         .build());   
		//設(shè)置虛擬機的策略
		  StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()   
		         .detectLeakedSqlLiteObjects()   
		         .detectLeakedClosableObjects()   
		         .penaltyLog()   
		         .penaltyDeath()   
		         .build());
		
		super.onCreate(savedInstanceState);
		//設(shè)置界面布局
		setContentView(R.layout.main);
		//初始化界面
        initView();
        //設(shè)置各種監(jiān)聽
		setListener();
	}
	/**
	 * 界面相關(guān)的各種設(shè)置
	 */
	private void initView() {
		//手機號碼編輯器
		phoneSecEditText = (EditText) findViewById(R.id.phone_sec);
		//
		resultView = (TextView) findViewById(R.id.result_text);
		queryButton = (Button) findViewById(R.id.query_btn);
	}
    /**
     * 設(shè)置各種事件監(jiān)聽的方法
     */
	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();
					// 將顯示查詢結(jié)果的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";
		// 創(chuàng)建HttpClient實例
		HttpClient client = new DefaultHttpClient();
		// 根據(jù)URL創(chuàng)建HttpPost實例
		HttpPost post = new HttpPost(requestUrl);

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 設(shè)置需要傳遞的參數(shù)
		params.add(new BasicNameValuePair("mobileCode", phoneSec));
		params.add(new BasicNameValuePair("userId", ""));
		try {
			// 設(shè)置URL編碼
			post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			// 發(fā)送請求并獲取反饋
			HttpResponse response = client.execute(post);

			// 判斷請求是否成功處理
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 解析返回的內(nèi)容
				String result = EntityUtils.toString(response.getEntity());
				// 將查詢結(jié)果經(jīng)過解析后顯示在TextView中
				resultView.setText(filterHtml(result));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 使用正則表達式過濾HTML標(biāo)記
	 * 
	 * @param source
	 *            待過濾內(nèi)容
	 * @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 使用HTTPClient調(diào)用Web請求(查詢手機號碼區(qū)域)


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 明溪县| 寻乌县| 项城市| 大理市| 武宁县| 当涂县| 潼关县| 揭东县| 祁阳县| 西畴县| 泾川县| 凭祥市| 微山县| 鄂温| 汶川县| 邓州市| 肥乡县| 秦安县| 和硕县| 通许县| 疏附县| 苏尼特左旗| 吕梁市| 潢川县| 丰都县| 芮城县| 光山县| 武宁县| 莱芜市| 温州市| 钟山县| 应城市| 塔河县| 霞浦县| 石台县| 池州市| 横山县| 莱西市| 方山县| 荆州市| 博野县|