httpclient 模拟登陆网站 获取网站内容程序

package org.apache.http.examples.client;

import java.io.IOException;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.*;
import org.apache.commons.httpclient.methods.*;

public class FormLoginDemo {
    static final String LOGON_SITE = "www.intellitrans.com.cn";
    static final int LOGON_PORT = 8081;
    static final String loginurl = "/zyzg/logon.do";
    static final String loginparematername = "userName";
    static final String loginparematerpass = "password";
    static final String username = "wangpx";
    static final String password = "111111";
    
    static final String getUrl = "/zyzg/hrmsub/hrm-deptlist.do";
    

    public static void main(String[] args) throws Exception {
        HttpClient client = imitateLogin(LOGON_SITE, LOGON_PORT, loginurl, loginparematername, loginparematerpass, username, password);
        // 访问所需的页面
        imitateGetUrl(client, getUrl);
    }
    
    //模拟等录
    private static HttpClient imitateLogin(String LOGON_SITE, int LOGON_PORT,
            String loginurl,String loginparematername,String loginparematerpass,String username,String password) throws IOException, HttpException {
        HttpClient client = new HttpClient();
        client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);
        // 模拟登录页面
        PostMethod post = new PostMethod(loginurl);
        NameValuePair name = new NameValuePair(loginparematername,username );
        NameValuePair pass = new NameValuePair(loginparematerpass,password );
        post.setRequestBody(new NameValuePair[] { name, pass });
        int status = client.executeMethod(post);
        System.out.println(post.getResponseBodyAsString());
        post.releaseConnection();
        // 查看cookie信息
        CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
        Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false,
                client.getState().getCookies());
        if (cookies != null)
            if (cookies.length == 0) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.length; i++) {
                    System.out.println(cookies[i].toString());
                }
            }
        return client;
    }
    //模拟等录 后获取所需要的页面
    private static void imitateGetUrl(HttpClient client, String getUrl)
            throws IOException, HttpException {
        PostMethod post2 = new PostMethod(getUrl);
        // GetMethod get = new
        // GetMethod("/social/article/gallery_show/p_104846/");
        client.executeMethod(post2);
        System.out.println(post2.getResponseBodyAsString());
        post2.releaseConnection();
    }
}

你可能感兴趣的:(apache,Social)