java 使用httpclient模拟登录

httpclient4.2.1
httpmime4.4

importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.util.ArrayList;
importjava.util.List;
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.CookieStore;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.cookie.Cookie;
importorg.apache.http.impl.client.AbstractHttpClient;
importorg.apache.http.impl.client.BasicCookieStore;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.impl.cookie.BasicClientCookie;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.util.EntityUtils;
importorg.junit.Test;
 
publicclass HttpClientLoginTest {
    @Test
    // 获取一个HTML页面的内容,一个简单的get应用
    publicvoid grabPageHTML() throwsException {
        HttpClient httpclient = newDefaultHttpClient();
        HttpGet httpget = newHttpGet("http://www.baidu.com/");
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        String html = EntityUtils.toString(entity, "GBK");
 
        // releaseConnection等同于reset,作用是重置request状态位,为下次使用做好准备。
        // 其实就是用一个HttpGet获取多个页面的情况下有效果;否则可以忽略此方法。
        httpget.releaseConnection();
 
        System.out.println(html);
    }
 
    // 下载一个文件到本地(本示范中为一个验证码图片)
    @Test
    publicvoid downloadFile() throwsException {
        String url = "http://www.lashou.com/account/captcha";
        File dir = newFile("D:\\TDDOWNLOAD");
        if(!dir.exists()) {
            dir.mkdirs();
        }
        String destfilename = "D:\\TDDOWNLOAD\\yz.png";
        HttpClient httpclient = newDefaultHttpClient();
        HttpGet httpget = newHttpGet(url);
        File file = newFile(destfilename);
        if(file.exists()) {
            file.delete();
        }
 
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        try{
            FileOutputStream fout = newFileOutputStream(file);
            intl = -1;
            byte[] tmp = newbyte[2048];
            while((l = in.read(tmp)) != -1) {
                fout.write(tmp);
            }
            fout.close();
        }finally{
            // 在用InputStream处理HttpEntity时,切记要关闭低层流。
            in.close();
        }
 
        httpget.releaseConnection();
    }
 
    @Test
    // Post方法,模拟表单提交参数登录到网站。
    // 结合了上面两个方法:grabPageHTML/downloadFile,同时增加了Post的代码。
    publicvoid login2Lashou() throwsException {
        // 第一步:先下载验证码到本地
        String url = "http://www.lashou.com/account/captcha";
        String destfilename = "D:\\TDDOWNLOAD\\yz.png";
        HttpClient httpclient = newDefaultHttpClient();
        HttpGet httpget = newHttpGet(url);
        File file = newFile(destfilename);
        if(file.exists()) {
            file.delete();
        }
 
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        try{
            FileOutputStream fout = newFileOutputStream(file);
            intl = -1;
            byte[] tmp = newbyte[2048];
            while((l = in.read(tmp)) != -1) {
                fout.write(tmp);
            }
            fout.close();
        }finally{
            in.close();
        }
        httpget.releaseConnection();
 
        // 第二步:用Post方法带若干参数尝试登录,需要手工输入下载验证码中显示的字母、数字
        BufferedReader br = newBufferedReader(newInputStreamReader(System.in));
        System.out.println("请输入下载下来的验证码中显示的数字...");
        String yan = br.readLine();
 
        HttpPost httppost = newHttpPost("http://www.lashou.com/account/login/");
        List params = newArrayList();
        params.add(newBasicNameValuePair("user_id","testuser007"));
        params.add(newBasicNameValuePair("pwd","asdfg123"));
        params.add(newBasicNameValuePair("yan", yan));
        params.add(newBasicNameValuePair("save_user","on"));
        params.add(newBasicNameValuePair("save_pwd","on"));
        params.add(newBasicNameValuePair("sub","登录"));
        httppost.setEntity(newUrlEncodedFormEntity(params));
 
        response = httpclient.execute(httppost);
        entity = response.getEntity();
        // 在这里可以用Jsoup之类的工具对返回结果进行分析,以判断登录是否成功
        String postResult = EntityUtils.toString(entity, "GBK");
        // 我们这里只是简单的打印出当前Cookie值以判断登录是否成功。
        CookieStore cookieStore = ((AbstractHttpClient) httpclient).getCookieStore();
        List cookies = ((AbstractHttpClient) httpclient)
                .getCookieStore().getCookies();
        for(Cookie cookie : cookies)
            System.out.println("cookie begin***\n" + cookie + "\n cookie end");
        httppost.releaseConnection();
 
        // 第三步:打开会员页面以判断登录成功(未登录用户是打不开会员页面的)
        String memberpage = "http://www.lashou.com/account/orders/";
        httpget = newHttpGet(memberpage);
        response = httpclient.execute(httpget); // 必须是同一个HttpClient!
        entity = response.getEntity();
        String html = EntityUtils.toString(entity, "GBK");
        httpget.releaseConnection();
 
        System.out.println(html);
    }
 
    @Test
    publicvoid testSystemIn() throwsIOException {
        BufferedReader reader = newBufferedReader(newInputStreamReader(
                System.in));
        String hello = reader.readLine();
        System.out.println(hello);
    }
 
    @Test
    // 设置已获取的cookie,查看需要登录后才能查看的页面
    publicvoid testGetinfoByLoginCookie() throwsException, IOException {
        DefaultHttpClient httpclient = newDefaultHttpClient();
        CookieStore cookieStore = newBasicCookieStore();
        BasicClientCookie cookie1 = newBasicClientCookie("ThinkID","5s4tmqem08gh091v3egoa7sqf7");
        cookie1.setDomain(".lashou.com");
        BasicClientCookie cookie2 = newBasicClientCookie("city_b","2419");
        cookie2.setDomain("lashou.com");
        BasicClientCookie cookie3 = newBasicClientCookie("client_key","1425104707wd157b4b24ff70adcb875a");
        cookie3.setDomain("lashou.com");
        BasicClientCookie cookie4 = newBasicClientCookie("login_name2","testuser007");
        cookie4.setDomain("lashou.com");
        BasicClientCookie cookie5 = newBasicClientCookie("pwd2","4c88a4062736c26572d3ec382868fa2b");
        cookie5.setDomain("lashou.com");
        cookieStore.addCookie(cookie1);
        cookieStore.addCookie(cookie2);
        cookieStore.addCookie(cookie3);
        cookieStore.addCookie(cookie4);
        cookieStore.addCookie(cookie5);
        List cookies = newArrayList();
        httpclient.setCookieStore(cookieStore);
         
        List cookieList = httpclient.getCookieStore().getCookies();
        for(inti=0;i
            System.out.println("cookie"+i+":"+cookieList.get(i));
        }
         
        // 设置已登录的cookie
        String memberpage = "http://www.lashou.com/account/orders/";
        HttpGet httpget = newHttpGet(memberpage);
        HttpResponse response = httpclient.execute(httpget); // 必须是同一个HttpClient!
        HttpEntity entity = response.getEntity();
        entity = response.getEntity();
        String html = EntityUtils.toString(entity, "GBK");
        httpget.releaseConnection();
 
        System.out.println(html);
    }
}

你可能感兴趣的:(Java开发)