Java语言使用HttpClient模拟浏览器登录

时间:2024-03-07 11:48:14

    使用HttpClient来模拟浏览器登录网站,然后可以进行操作,比如发布信息等

    第一步:获取实际的post网址,(不考虑复杂情况下)

  1、需要使用到firefox的httpfox插件,httpfox中clear一下,然后start开始捕获

  2、切换回网页的登录页面,开始输入自己的账号密码登录,登录成功后切回httpfox中stop,查看最近的post方法中包含的Post Data数据,和此post方法的url网址,

  3、这样就得到了模拟登录时需要Post的数据参数(Parameter)值(Value),以及实际Post的网址URL

    第二步,使用HttpClient来登录

  1、简单核心代码如下

  

 1         CloseableHttpClient httpclient = HttpClients.createDefault();
 2         List<NameValuePair> postData = new ArrayList<NameValuePair>();
 3         //这里可能有多个参数
 4         postData.add(new BasicNameValuePair("username", "username"));
 5         postData.add(new BasicNameValuePair("password", "password"));
 6         //URL是实际的post地址,使用httpFox得到
 7         HttpPost httppost = new HttpPost(URL); 9         try {11                 httppost.setEntity(new UrlEncodedFormEntity(postData, "GBK"));
12                 response = httpclient.execute(httppost);
15         } catch (IOException e) {
16         } finally {
17             closeIO(response);
18         }