Apache Httpclient + NTLM身份验证

3

我有一个客户需要通过HTTPS POST将文件上传到服务器。它使用代理,以下是我的代码:

public void upload() throws Exception {

    //create default client
    DefaultHttpClient client = new DefaultHttpClient();

    //set proxy authentication if specified
    if (proxy.equals("yes") && proxyAuth.equals("yes")){
    client.getCredentialsProvider().setCredentials(
            new AuthScope(address, port),
            new UsernamePasswordCredentials(proxyUsername, proxyPassword));
    }

    //set proxy if specified
    if (proxy.equals("yes")){
        HttpHost proxy = new HttpHost(address, port);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
    }

    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File dir = new File(inputFilePath);
    File[] fileArray = dir.listFiles(); 
    File file = fileArray[0];

    FileBody uploadFilePart = new FileBody(file);

    entity.addPart("file", uploadFilePart);
    entity.addPart("username", new StringBody(username));
    entity.addPart("password", new StringBody(password));

    post.setEntity(entity);

    //execute post and get response
    String response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8");

    client.getConnectionManager().shutdown();

    log4j.info(response);

    if(!response.substring(0, 3).equalsIgnoreCase("200")){
        Exception e = new Exception("An error has occurred server side: ");
        throw e;
    }
}

现在问题是有时它可以完美地工作,但有时我会得到以下错误:

org.apache.http.impl.client.AbstractAuthenticationHandler.selectScheme(AbstractAuthenticationHandler.java:149) - 不支持身份验证方案ntlm"


你尝试过按照http://hc.apache.org/httpcomponents-client-ga/ntlm.html的说明操作吗? - DanLebrero
尝试过了,但仍然存在相同的问题。 - user732362
如果您正在使用httpclient 3,您可以使用此工具来简化此类身份验证场景 https://github.com/DovAmir/httpclientAuthHelper - dov.amir
2个回答

4

你在这里发布的链接是用于使用Samba NTLM实现的。现在你应该可以使用Apache自己的实现(4.7):https://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html - Almer

2

尝试使用以下代码替代:

使用NTCredentials代替UsernamePasswordCredentials,并添加"localhostname"和"domain"参数:

new NTCredentials(proxyUsername, proxyPassword, "localhostname", "domain")


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接