3

我正在尝试使用 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 的一些 jarfile 的帮助下,我也尝试了它。

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();

    }

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

公共字符串加载页面(字符串 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();

}
4

2 回答 2

2

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

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

如果最新情况是您的情况,您应该查看此Client HTTP Programming Primer其中包括

  • 在网络表单中输入用户名和密码,然后点击“登录”按钮
于 2012-05-08T13:30:29.437 回答
0

实际上我所做的是正确的。我很幸运地找到了解决方案。我不知道为什么,但我不得不in.readLine();

in.readLine();

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

在我登录后获取 Streams。如果我在 While 之前不执行此行。我在登录之前获取 Streams,尽管我已经登录。

于 2012-05-09T07:58:43.327 回答