gam*_*zii 5 java apache authentication httpclient basic-authentication
两个相关的问题,我正在使用Apache HTTP Client 4.x API。myHttpPost是HttpPost的实例,而myHttpClient是HttpClient的实例。我正在尝试使用基本身份验证发送请求。所以我有一个HttpClient并创建一个HttpPost。
设置基本身份验证标头的“蛮力”方式似乎是在HttpPost标头中进行设置。
String encoding = Base64Encoder.encode("username" + ":" + "password");
myHttpPost.setHeader("Authorization", "Basic " + encoding);
Run Code Online (Sandbox Code Playgroud)
上面的示例来自另一个堆栈溢出问题(现在找不到指向它的链接)。关于Base64Encoder类-我可以在哪个包中找到它,或者从哪里下载它?
主要问题-我希望使用以下代码以更美观的方式进行基本身份验证:
myHttpClient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC),
new UsernamePasswordCredentials("username", "password")
);
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用。那么上面的第一个示例是使用Apache HTTP Client 4.0进行基本身份验证的正确方法吗?还是有一种更清洁/更简单的方法。
关于 Base64Encoder 类 - 我可以在哪个包中找到它或者从哪里下载它?
Base64Encoder 可以来自各个地方,我找不到与您的静态encode方法匹配的东西。
至于凭证,您需要在您的 上进行scheme设置,如下所示:BasicAuthScope
myHttpClient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "basic"),
new UsernamePasswordCredentials("username", "password")
);
Run Code Online (Sandbox Code Playgroud)
或者
myHttpClient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC),
new UsernamePasswordCredentials("username", "password")
);
Run Code Online (Sandbox Code Playgroud)