您的位置:首页 > 理论基础 > 计算机网络

Android平台HttpClient的使用-手机号码归属地查询

2016-01-19 14:12 531 查看

  Android平台主要提供了四种数据存储方式:Shared Preferences、文件存储、Sqlite存储和网络存储。其中:

      1)Shared Preferences 一个轻量级的键-值存储机制,专门用于存储键-值对数据,并且仅可以存储基本的数据类型(boolean、int、long、float和String);通常使用它来存储应用程序的配置信息。

      2)文件存储 通过FileInputStream和FileOutputStream对文件进行操作,在Android中,文件是一个应用程序私有的,一个应用程序无法读写其它应用程序的文件。

      3)SQLite存储 SQLite是一款轻型的数据库,支持标准SQL。它的设计目标是嵌入式的,占用资源非常的低,在嵌入式设备中,只需要几百K的内存就够了。Android平台也为我们提供了SQLite数据库。

      4)网络存储 以上3种方式数据均存储在手机上,而网络存储的数据是存储在远程服务器上,手机客户端通过联接到网络来存储和获取数据。
      今天要讲解的HttpClient正是常用的网络存储工具之一。记得最早接触HttpClient是在两年前,当时要做一个垂直搜索引擎,数据自然是来源于互联网,通过一个爬虫系统不断从指定网站上爬取感兴趣的数据,然后通过Lucene搜索引擎框架实现海量数据的快速检索。而爬虫系统最开始是想采用开源的爬虫框架Heritrix来实现,但接触一段时间后发现Heritrix过于庞大,而且是作为一个独立的系统运行,不方便嵌入到现有的系统中,再加上学习成本高,最后还是选择了“HttpClient + HtmlParser”来实现的小型爬虫系统;其中HttpClient可以模拟HTTP的POST和GET请求,用于从指定网站获取网页数据,而HtmlParser用于解析爬取到的页面,过滤HTML标记,取得最终数据。

      是不是发现HttpClient还挺强大的?让我们看看它是什么来头。"HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议"。如果你以前没有接触过HttpClient,那么你只需要简单记住两点就可以了:1)HttpClient是一个HTTP协议开发包;2)HttpClient不是Android的专利。

      HttpClient的功能介绍:
            1)实现了HTTP请求的所有方法(如GET、POST、PUT、HEAD 等);

            2)支持自动转向;

            3)支持 HTTPS 协议;

            4)支持代理服务器等

      HttpClient的基本使用(以POST请求为例):

            1)创建HttpClient实例(类似于浏览器客户端);

                        HttpClient client = new DefaultHttpClient();

            2)创建HttpPost请求,需要向HttpPost的构造方法传入所请求的URL;

                        HttpPost post = new HttpPost(requestUrl);
            3)发出POST请求(调用HttpClient的execute()方法,execute()的参数为HttpPost实例);

                        HttpResponse response = client.execute(post);

            4)读取返回结果;

            5)释放连接;

            6)对返回的结果进行处理。

      在Android平台上使用HttpClient,并不需要添加额外的jar包,因为Android平台吸收了许多优秀的开源框架,其中就包括HttpClient。(注意我写的是吸收,不是收购,两码事),下面就来看一个Android平台使用HttpClient的例子。
1)首先来看布局文件res/layout/main.xml

     

[xhtml]
view plaincopyprint?

<?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"  
    />  
    <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"
/>
<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>

2)Activity的代码

     


[java]
view plaincopyprint?

package com.liufeng.web.activity;  
  
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.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.TextView;  
  
/** 
 * HttpClient运用之手机号码归属地查询 
 *  
 * @author liuyq 
 * @date 2011-05-11 
 */  
public class MainActivity extends Activity {  
    private EditText phoneSecEditText;  
    private TextView resultView;  
    private Button queryButton;  
  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
  
        phoneSecEditText = (EditText) findViewById(R.id.phone_sec);  
        resultView = (TextView) findViewById(R.id.result_text);  
        queryButton = (Button) findViewById(R.id.query_btn);  
  
        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.liufeng.web.activity;

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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
* HttpClient运用之手机号码归属地查询
*
* @author liuyq
* @date 2011-05-11
*/
public class MainActivity extends Activity {
private EditText phoneSecEditText;
private TextView resultView;
private Button queryButton;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

phoneSecEditText = (EditText) findViewById(R.id.phone_sec);
resultView = (TextView) findViewById(R.id.result_text);
queryButton = (Button) findViewById(R.id.query_btn);

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();
}
}

3)在AndroidManifest.xml中添加访问网络的权限

     


[xhtml]
view plaincopyprint?

<uses-permission android:name="android.permission.INTERNET" />   

<uses-permission android:name="android.permission.INTERNET" />


4)运行结果截图

     




备注:是不是发现HttpClient很容易使用呢?其实,上面所讲解的只是HttpClient最基本的功能(发起POST请求);我们在浏览器客户端所执行的大多数操作HttpClient都能够模拟,例如:提交表单、查询数据、上传下载文档、页面跳转、Session存储等。比如大家经常玩“抢车位”、“偷菜”,就可以通过HttpClient编程自动实现。(其实这就相当于外挂的原型了,尝试一下可以,小心被封号!)

原文出处http://blog.csdn.net/lyq8479/article/details/6413216
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息