Java模拟Web登陆(Post模式)

HttpURLConnection.setRequestMethod设置登录模式为POST(字符串大写)

HttpURLConnection.setRequestProperty设置登陆配置

HttpURLConnection.setDoOutput(true)打开输出,向服务器输出参数(POST方式、字节)(写参数之前应先将参数的字节长度设置到配置”Content-Length”<字节长度>)

HttpURLConnection.setDoInput(true)打开输入,从服务器读取返回数据

HttpURLConnection.getHeaderFields()).get(“Set-Cookie”)用于迭代读取Cookie,为以后使用

HttpURLConnection.getHeaderField(“Set-Cookie”)也可用于读取Cookie,但不一定能读取完全

 

具体实现部分代码(登陆并获取Cookie)

   byte []post = submit.getBytes(“utf8”);
   conn = (HttpURLConnection) (new URL(login)).openConnection();
   
   conn.setRequestMethod(“POST”);
   conn.setRequestProperty(“User-Agent”, “Mozilla/5.0”);
   conn.setDoOutput(true);
   conn.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);
   conn.setRequestProperty(“Content-Language”, “zh-cn”);
   conn.setRequestProperty(“Content-Length”, String.valueOf(post.length));
   conn.setRequestProperty(“Connection”, “keep-alive”);
   conn.setRequestProperty(“Cache-Control”, “no-cache”);
   
   conn.getOutputStream().write(post);
   conn.getOutputStream().flush();
   conn.getOutputStream().close();
   conn.connect();
   /*
    * get cookie information
    */
   List<String> list = ((Map<String, List<String>>)conn.getHeaderFields()).get(“Set-Cookie”);
   for(String temp : list) {
    cookies += temp + “; “;
   }
   conn.disconnect();

之后使用只需

   conn.setRequestProperty(“Cookie”, cookies);

即可不许每次都登陆

 

GET方式登录只需将参数配置到url链接之中即可

此条目发表在JAVA SE分类目录,贴了, 标签。将固定链接加入收藏夹。