Java相当于NetworkCredential

时间:2015-09-15 12:52:25

标签: java c# authentication

在C#代码中,我们使用网络身份验证:

req = HttpWebRequest.Create(Url)
req.Method = "POST"
req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate")
req.Credentials = New NetworkCredential(Username, Password)

我们需要在Java中实现它。我尝试过两种方法,但它不起作用:

  1. httppost.setHeader("授权","基本" +"用户名:密码");

  2. Authenticator.setDefault(new PaswordAuthentication());

  3. 但两者都不起作用。 任何领导都将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

虽然以下link回答了问题,但它没有显示使用HttpClientBuilder的完整解决方案。以下是从需要Windows身份验证的IIS服务器获取索引文件的完整示例。

package test;

import java.util.*;

import org.apache.http.*;
import org.apache.http.auth.*;
import org.apache.http.client.*;
import org.apache.http.client.config.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.util.*;

public class Test 
{
    public static void main(String[] args)
    {
        try
        {
            RequestConfig requestConfig = RequestConfig.custom()
                .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM))
                .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
                .build();

            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                new NTCredentials("USERNAME", "PASSWORD", "HOSTNAME", "DOMAIN"));

            HttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credentialsProvider)
                .setDefaultRequestConfig(requestConfig)
                .build();

            HttpHost target = new HttpHost("localhost", 80, "http");
            HttpGet httpget = new HttpGet("/");
            HttpResponse r = httpclient.execute(target, httpget);
            HttpEntity e = r.getEntity();
            String responseString = EntityUtils.toString(e, "UTF-8");
            System.out.println(responseString);
        }
        catch (Exception ex)
        {
            System.out.println(ex.getMessage());
        }
    }
}

答案 1 :(得分:0)

您是否尝试过org.apache.commons.httpclient.NTCredentials

这里有link个样本。