需要模拟登录的页面核心源码:
代码:
package com.test;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class LoginTest {
@SuppressWarnings("static-access")
public void login(String userName,String pwd)throws Exception{
//第一次请求
Connection con=Jsoup.connect("https://passport.csdn.net/account/login");//获取连接
con.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");//配置模拟浏览器
Response rs= con.execute();//获取响应
Document d1=Jsoup.parse(rs.body());//转换为Dom树
List et= d1.select("#fm1");//获取form表单,可以通过查看页面源码代码得知
//获取,cooking和表单属性,下面map存放post时的数据
Map datas=new HashMap<>();
for(Element e:et.get(0).getAllElements()){
if(e.attr("name").equals("username")){
e.attr("value", userName);//设置用户名
}
if(e.attr("name").equals("password")){
e.attr("value",pwd); //设置用户密码
}
if(e.attr("name").length()>0){//排除空值表单属性
datas.put(e.attr("name"), e.attr("value"));
}
}
/*
* 第二次请求,post表单数据,以及cookie信息
*/
Connection con2=Jsoup.connect("https://passport.csdn.net/account/login");
con2.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
//设置cookie和post上面的map数据
Response login=con2.ignoreContentType(true).method(Method.POST).data(datas).cookies(rs.cookies()).execute();
//打印,登陆成功后的信息
System.out.println(login.body());
//登陆成功后的cookie信息,可以保存到本地,以后登陆时,只需一次登陆即可
Map map=login.cookies();
for(String s:map.keySet()){
LoginTest testw = new LoginTest();
String str = s+" "+map.get(s);
testw.WriteFile("D:\\cookie.txt", str);
System.out.println(s+" "+map.get(s));
}
}
//将Cooie信息写入记事本文件
public static void WriteFile(String file, String conent) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true)));
out.write(conent+"\r\n");
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//测试类
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
LoginTest test = new LoginTest();
test.login("XXX", "XXX"); //输入用户名和密码
}
}
截图:
登录成功的信息
登录形成的Cookie信息
保存在本地的Cookie信息(已檫除个人隐私信息)
总结:
模拟登陆之后,你就可以随心所欲的操作了。可以写个发博客的小程序或者是刷访问量之类的小技活~