Java上的HTML身份验证不起作用

时间:2012-04-30 18:22:21

标签: java http authentication

我正在尝试使用Apache的一些jar文件向网站发送我的用户名或密码,并尝试使用我的方法“loadpage”从网站上读取所有内容。

它不起作用。我执行我的方法“loadpage”后。我仍然从主页面获取Streams,我不需要登录。我想在登录后拥有Streams。

  public static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope("https://justawebsite", 8080),
                    new UsernamePasswordCredentials("username","password"));

            HttpGet httpget = new HttpGet("https://justawebsite");

            System.out.println("executing request" + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

我在没有Apache的一些jar文件的帮助下也尝试了它。

public  void LogIn(String url1) throws Exception{
        URL url = new URL(url1);

        String userPassword = "username"+":"+"password";
        String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
        //con.setRequestProperty("Cookie", "JSESSIONID="+getSid());

        URLConnection con = url.openConnection();
        //con.connect();
        con.setRequestProperty("Cookie", "JSESSIONID=" + encoding);


        con.connect();

    }

我的方法加载页面:它有效,因为我尝试了其他一些不需要身份验证的网站。

public String loadPage(String url)抛出异常{

    URLConnection con = new URL(url).openConnection();
    StringBuilder buffer = new StringBuilder();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line;
    while((line=in.readLine())!= null){
        buffer.append(line);
    }
    in.close();
    return buffer.toString();

}

2 个答案:

答案 0 :(得分:2)

您应首先检查Behe指出的网站使用的身份验证类型,因为有Web Authentication Types不同。

您的第一个示例是使用基本身份验证,但该网站可能需要某种基于表单的身份验证。

如果您的情况属实,请查看此Client HTTP Programming Primer,其中包括

  
      
  • 在网络表单中输入用户名和密码,然后点击“登录”按钮
  •   

答案 1 :(得分:0)

Actuualy我所做的是正确的。我发现解决方案只是运气好。我不知道为什么,但我必须在

之前写一次in.readLine();
in.readLine();

while((line=in.readLine()) != null){
buffer.append(line);
}
in.close()

在我登录后获取Streams。如果我之前没有这样做,那么我在登录之前得到了Streams,尽管我已经登录了。