Java通过httpclient模拟登录

 

方法1:

import org.apache.commons.httpclient.Cookie;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.NameValuePair;

import org.apache.commons.httpclient.cookie.CookiePolicy;

import org.apache.commons.httpclient.methods.GetMethod;

import org.apache.commons.httpclient.methods.PostMethod;



public class HttpLogin {



    public static void main(String[] args) {

        // 登陆 Url

        String loginUrl = "http://passport.mop.com/?targetUrl=http://hi.mop.com/?&g=1447141423230&loginCheck=UNLOGINED";

        // 需登陆后访问的 Url

        String dataUrl = "http://hi.mop.com/?";

        HttpClient httpClient = new HttpClient();



        // 模拟登陆,按实际服务器端要求选用 Post 或 Get 请求方式

        PostMethod postMethod = new PostMethod(loginUrl);



        // 设置登陆时要求的信息,用户名和密码

        NameValuePair[] data = { new NameValuePair("loginName", "chzeze123"), 

                                new NameValuePair("loginPasswd", "**") };

        postMethod.setRequestBody(data);

        try {

            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略

            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

            int statusCode=httpClient.executeMethod(postMethod);

                             

            // 获得登陆后的 Cookie

            Cookie[] cookies = httpClient.getState().getCookies();

            StringBuffer tmpcookies = new StringBuffer();

            for (Cookie c : cookies) {

                tmpcookies.append(c.toString() + ";");

                System.out.println("cookies = "+c.toString());

            }

            if(statusCode==302){//重定向到新的URL

                System.out.println("模拟登录成功");

                // 进行登陆后的操作

                GetMethod getMethod = new GetMethod(dataUrl);

                // 每次访问需授权的网址时需带上前面的 cookie 作为通行证

                // (httpClient客户端 会自动带上  如不是特殊要求一般不进行设置)

                getMethod.setRequestHeader("cookie", tmpcookies.toString());

                // 你还可以通过 PostMethod/GetMethod 设置更多的请求后数据

                // 例如,referer 从哪里来的,UA 像搜索引擎都会表名自己是谁,无良搜索引擎除外

                postMethod.setRequestHeader("Referer", "http://passport.mop.com/");

                postMethod.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");

                httpClient.executeMethod(getMethod);

                // 打印出返回数据,检验一下是否成功

                String text = getMethod.getResponseBodyAsString();

                System.out.println(text);

            }

            else {

                System.out.println("登录失败");

            }

        }

        catch (Exception e) {

            e.printStackTrace();

        }

    }

}

方法2:

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Test  {

    public static void main(String[] args) throws IOException {
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        String line = null;
        //两个页面参数
        //据我观察这个url不变
        String backUrl = "http%3A%2F%2Fredmine.tvbanywhere.net%2Fredmine%2F";
        String authenticityToken = null;

        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //get请求访问这个url是页面
        //获取auth_token
        HttpGet getParam = new HttpGet("http://redmine.tvbanywhere.net/redmine/login");
        CloseableHttpResponse response1 = httpClient.execute(getParam);
        InputStream inputStream1 = response1.getEntity().getContent();
        inputStreamReader = new InputStreamReader(inputStream1);
        reader = new BufferedReader(inputStreamReader);
        while ((line = reader.readLine())!= null){
            if (line.contains("name=\"authenticity_token\"")){
                System.out.println(line);
                String sub1 = line.substring(line.indexOf("value=\"") + 7);
                authenticityToken = sub1.substring(0, sub1.indexOf("\""));
            }
        }
        reader.close();
        inputStreamReader.close();
        inputStream1.close();
        //post 请求是登录操作
        HttpPost dologin = new HttpPost("http://redmine.tvbanywhere.net/redmine/login");
        List list = new ArrayList();
        list.add(new BasicNameValuePair("authenticity_token",authenticityToken));
        list.add(new BasicNameValuePair("back_url",backUrl));
        list.add(new BasicNameValuePair("username","[email protected]"));
        list.add(new BasicNameValuePair("password","[email protected]"));
        UrlEncodedFormEntity urlEncodedFormEntity = null;
        urlEncodedFormEntity = new UrlEncodedFormEntity(list);
        dologin.setEntity(urlEncodedFormEntity);
        CloseableHttpResponse response2 = httpClient.execute(dologin);

        HttpGet get1 = new HttpGet("http://redmine.tvbanywhere.net/redmine/[email protected]");
        CloseableHttpResponse response3 = httpClient.execute(get1);
        System.err.println("get" + get1.getURI());
        InputStream inputStream3 = response3.getEntity().getContent();
        inputStreamReader = new InputStreamReader(inputStream3);
        reader = new BufferedReader(inputStreamReader);
        while ((line = reader.readLine()) != null){
            System.out.println(line);
        }
    }
}

 

你可能感兴趣的:(java)