如何使用java模拟登录

How can I use java to simulate login

我想使用httpurlconnection class 来模拟登录一个网站。我试着 捕获数据包以获取请求 header 并将其全部放入我的程序。但是这段代码无法从服务器获取cookie。

    String username = "。。。。。。;
    String password = ".。。。。";
    String param = "username="+username+"&pwd="+password+"&usertype=xuesheng&Submit=+%B5%C7%C2%BD+";
    HttpURLConnection connection = (HttpURLConnection)urlx.openConnection();
    connection.setRequestProperty("Host","jwc.ecjtu.jx.cn:8080");
    connection.setRequestProperty("Connection","keep-alive");
    connection.setRequestProperty("Content-Length","74");
    connection.setRequestProperty("Cache-Control","max-age=0");
    connection.setRequestProperty("Content-Length","http://jwc.ecjtu.jx.cn:8080");
    connection.setRequestProperty("Upgrade-Insecure-Requests","1");
    connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36");
    connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    connection.setRequestProperty("DNT","1");
    connection.setRequestProperty("Referer","http://jwc.ecjtu.jx.cn:8080/jwcmis/assess/");
    connection.setRequestProperty("Accept-Encoding","gzip, deflate");
    connection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST"); 

这是我发送给服务器的密钥代码。 我应该怎么做才能模拟登录成功?我还应该添加什么代码?

我认为你应该阅读 CookieHandler

javahttp://www.mkyong.com/java/how-to-automate-login-a-website-java-example/

中有模拟登录的解决方案示例

我没有得到 cookie 的原因是我 post 的网站将重定向 link,我没有设置 setInstanceFollowRedirects(false)。我得到错误的回应。所以我没有得到 cookie