gpt4 book ai didi

Java 相当于 NetworkCredential

转载 作者:行者123 更新时间:2023-11-30 07:56:38 25 4
gpt4 key购买 nike

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

但是两者都不起作用。任何线索都将受到高度赞赏。

最佳答案

虽然下面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());
}
}
}

关于Java 相当于 NetworkCredential,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32586626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com