0

我正在尝试使用Apache HttpClient API 来访问 Atlassian Confluence wiki 页面。

这是我的代码:

public class ConcfluenceTest{

    public static void main(String[] args) {
        String pageID = "107544635";
        String hostName = "valid_hostname";
        String hostScheme = "https";
        String username = "verified_username";
        String password = "verified_password";
        int port = 443;

        //set up the username/password authentication
        BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
            new AuthScope(hostName, port, AuthScope.ANY_REALM, hostScheme),
            new UsernamePasswordCredentials(username, password));

        HttpClient client = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credsProvider)
            .build();

        try {

            HttpGet getRequest = new HttpGet("valid_url");
            System.out.println(getRequest.toString());

            HttpResponse response = client.execute(getRequest);

            //Parse the response
            BufferedReader rd = new BufferedReader(
                new     InputStreamReader(response.getEntity().getContent()));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }

            System.out.println(result.toString());

        } catch (UnsupportedEncodingException e) {
            System.out.println(e.getStackTrace());
        } catch (IOException e) {
            System.out.println(e.getStackTrace());
        }

    }
}

当我尝试执行此代码时,打印的响应是登录屏幕的 HTML,这意味着身份验证失败。但是,当我将 URL 提供给不限于注册用户的页面(即不需要凭据)时,此代码确实会返回正确的响应。我还尝试了端口/方案的所有排列。

有人能告诉我我错过了什么吗?

4

1 回答 1

0

Afaik,如果支持 http-basic-auth,类似

user:password@server:port/path 

也应该工作。您可以查看它是否适用于浏览器。

如果 Confluence 不支持基本身份验证,请使用 firebug 找出登录表单的操作(例如路径,类似/dologin.action)、方法(POST)和用户/密码字段的名称。

使用该信息,您可以创建如下请求:

HttpPost httpPost = new HttpPost(fullFormActionUrlWithServerAndPort);
List <NameValuePair> nvp = new ArrayList <NameValuePair>();
nvp.add(new BasicNameValuePair("name-of-the-user-field", "your-user-name"));
nvp.add(new BasicNameValuePair("name-of-the-pass-field", "your-password"));
httpPost.setEntity(new UrlEncodedFormEntity(nvp));
于 2015-09-01T11:22:18.663 回答