2

我正在尝试使用 HttpClient 登录到 HTTPS URL,但失败了。我可以就我的问题寻求帮助吗?这是我写的代码。此代码能够获取 cookie 部分,但未登录。登录后,我需要从登录页面获取一些数据。

DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("http://www.example.com");
    HttpResponse response = httpclient.execute(httpget);
         HttpEntity entity = response.getEntity();
    System.out.println("Initial set of cookies:");
         List<Cookie> cookies = httpclient.getCookieStore().getCookies();
         if (cookies.isEmpty()) {
             System.out.println("None");
         } else {
             for (int i = 0; i < cookies.size(); i++) {
                 System.out.println("- " + cookies.get(i).toString());
             }
         }
         
         HttpPost httpost = new HttpPost("https://www.example.com/jsp/login.jsp");

         List <NameValuePair> nvps = new ArrayList <NameValuePair>();
         nvps.add(new BasicNameValuePair("username", "xxx"));
         nvps.add(new BasicNameValuePair("password", "xxx"));

         httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

         response = httpclient.execute(httpost);
         entity = response.getEntity();

         System.out.println("Login form get: " + response.getStatusLine());
         EntityUtils.consume(entity);

         System.out.println("Post logon cookies:");
         cookies = httpclient.getCookieStore().getCookies();
         if (cookies.isEmpty()) {
             System.out.println("None");
         } else {
             for (int i = 0; i < cookies.size(); i++) {
                 System.out.println("- " + cookies.get(i).toString());
             }
         }
4

1 回答 1

0

您可能缺少登录按钮和更多名称值对。我不确定您的按钮被称为什么或随它发送的值。

List <NameValuePair> nvps = new ArrayList <NameValuePair>();
         nvps.add(new BasicNameValuePair("username", "xxx"));
         nvps.add(new BasicNameValuePair("password", "xxx"));
         nvps.add(new BasicNameValuePair("button", "Login"));

我会下载TamperData,然后在 TamperData 启动时访问您的网页并登录。使用它来查看您登录的 POST。可能会发送您丢失的名称值对。

于 2016-02-17T15:48:52.510 回答