这个类的功能:
1. 利用httpClient开源组件,简化访问web
2. 利用sogou的开放查询接口,进行手机号码归谁查询
注意此处用的HttpClient的版本号为3.1
目前新版本有些api接口做了调整,暂时没有时间测试
1. 利用httpClient开源组件,简化访问web
2. 利用sogou的开放查询接口,进行手机号码归谁查询
注意此处用的HttpClient的版本号为3.1
目前新版本有些api接口做了调整,暂时没有时间测试
/**
*
*/
package demo;
import java.io.IOException;
import java.util.Scanner;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* @author sean
*
* @since 2009/05/09
*
* 使用HttpClient组件,连接web
* 查询手机号码归属地
* 服务器端是由sogou开发的查询模块
*
*/
public class SimpleHttpClient {
static HttpMethod method = null;
static String reponse = null;
static String phone; //需要查询的手机号码
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
//此处简单处理,循环获得用户的电话号码输入
do {
System.out.println("输入您的电话号码");
phone = scanner.next();
query();
System.out.println("******************************");
} while (true);
}
/**
* 进行查询
* 1. 初始化httpclient对象
* 2. 设置host, port, protocol
* 3. 获得postMethod
* 4. client.executeMethod(),执行查询工作
*/
private static void query() {
// TODO Auto-generated method stub
String host = "www.sogou.com";
//实例化一个httpClient对象
HttpClient client = new HttpClient();
//设置host, port, protocol
client.getHostConfiguration().setHost(host, 80, "http");
method = getPostMethod(phone);
try {
client.executeMethod(method);
System.out.println(method.getStatusLine());
reponse = method.getResponseBodyAsString();
} catch (HttpException e) {
System.out.println("httpexception");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 释放当前连接
method.releaseConnection();
// 根据html源码提取需要的手机号码归谁地信息
if (reponse.contains("手机号")) {
int beginIndex = reponse.indexOf("手机号:");
int endIndex = reponse.indexOf("用户");
reponse = reponse.substring(beginIndex, endIndex);
reponse = reponse.replace("<p>", "");
reponse = reponse.replace("</p>", "");
System.out.println(reponse);
} else {
System.out.println("error");
}
}
/**
* 使用 POST 方式提交数据
* 1. 获得post对象,需要设置相对路径作为
*
* @return
*/
private static HttpMethod getPostMethod(String phone) {
PostMethod post = new PostMethod("/features/mobile.jsp");
//类似hashmap的key, value, 成对保存在simcard中
NameValuePair simcard = new NameValuePair("query", phone);
post.setRequestBody(new NameValuePair[] { simcard });
return post;
}
}