使用httpclient java登录https网址

时间:2012-09-12 10:14:19

标签: apache-httpclient-4.x

我正在尝试使用httpclient登录到https网址但是失败了。我得到了解决问题的方法吗?这是我写的代码。这段代码能够获取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());
             }
         }

1 个答案:

答案 0 :(得分: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。可能存在您丢失的正在发送的名称值对。