httpclient 获取表单提交返回数据(取table 中的数据)

http://haoma.imobile.com.cn/index.php?mob= 为例

mob 是手机号码参数.

 

通过 httpClient 进行页面的请求,并返回结果页面的源码:

View Code
 1 public class SimpleHttpClient {
 2 
 3     public static void main(String[] args) throws HttpException, IOException,
 4             ParserException {
 5         HttpClient client = new HttpClient();
 6         client.getHostConfiguration().setHost("haoma.imobile.com.cn", 80,
 7                 "http");
 8 
 9         System.out.println("method:" + getPostMethod().getStatusLine());
10         HttpMethod method = getPostMethod();
11         client.executeMethod(method);
12         String response = new String(method.getResponseBodyAsString().getBytes(
13                 "gbk"));
14     }
15         
16     private static HttpMethod getPostMethod() {
17             PostMethod post = new PostMethod("/index.php");
18             NameValuePair simcard = new NameValuePair("mob", "13979146891");
19             post.setRequestBody(new NameValuePair[] { simcard });
20             return post;
21         }
22     
23 }

返回的页面:


接下来,通过htmlparser ,解析源码中的table内容:

View Code
 1     /**
 2      * html源码处理
 3      * @param response
 4      * @throws ParserException
 5      */
 6     private static void deal_resource(String response) throws ParserException {
 7 
 8         Parser parser = Parser.createParser(response, "gbk");
 9         HtmlPage page = new HtmlPage(parser);
10 
11         parser.visitAllNodesWith(page);
12 
13         NodeList nodeList = page.getBody();
14 
15         NodeFilter filter = new TagNameFilter("table");
16 
17         nodeList = nodeList.extractAllNodesThatMatch(filter, true);
18 
19         TableTag tag = (TableTag) nodeList.elementAt(0);
20 
21         for (int i = 0; i < tag.getChildCount(); i++) {
22             NodeList nodelist1 = tag.getChild(i).getChildren();
23             if (nodelist1 != null) {
24                 for (int j = 0; j < nodelist1.size(); j++) {
25                     System.out.println("nodeList.elementAt(i).toHtml():"
26                             + nodelist1.elementAt(j).toPlainTextString());
27                 }
28             }
29         }
30     }

 

 

源码下载:HttpClientDemo.zip

posted on 2012-12-07 14:50  双耳  阅读(603)  评论(0)    收藏  举报

导航