我需要访问一个这样工作的API:
curl https://api.com/ratings/v1/ -u [your token here]:
令牌是应该传递给HttpGet
请求的用户名。我试图用以下方式使用java:
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("usrname", "passwrd"));
HttpHost proxy = new HttpHost("proxy.com", 8080, "http");
HttpClient httpClient = HttpClients.custom().setProxy(proxy).setDefaultCredentialsProvider(credentialsProvider).build();
HttpGet toesGet = new HttpGet("https://api.com/ratings/v1/");
toesGet.setHeader("Accept", "Application/Json");
toesGet.addHeader("Username", "[your token here]");
try {
HttpResponse toes = httpClient.execute(toesGet);
System.out.println(toes.getStatusLine());
System.out.println(toes.getEntity().toString());
} catch (Exception e) {
e.printStackTrace();
}
我是后面的代理,因此我创建了一个HttpHost
,其中包含代理详细信息,为HttpClient
对象设置代理,并使用credentialsProvider
传递代理身份验证的凭据以下代码行:
HttpHost proxy = new HttpHost("proxy.com", 8080, "http");
HttpClient httpClient = HttpClients.custom().setProxy(proxy).setDefaultCredentialsProvider(credentialsProvider).build();
我正在将username
传递给HttpGet
,只需添加header
:
toesGet.addHeader("Username", "[your token here]");
当我运行代码时,我得到了这样的回复: HTTP/1.1 401 UNAUTHORIZED
这表明我没有以正确的方式将username
传递给HttpGet
请求(或者这意味着什么?)。那么将用户名传递给get请求的正确方法是什么?
任何帮助将不胜感激,谢谢!
注意:我在credentialsProvider中设置的usrname
和passwrd
用于代理身份验证。它们与HttpGet请求本身无关。我需要传递的令牌与凭证中提供的usrname
不同。
答案 0 :(得分:1)
我想,您的服务器使用基本身份验证,然后您需要添加“授权”标头而不是“用户名”:
String user = "[your token here]";
String pwd = ""; // blank
toesGet.addHeader("Authorization", "Basic " + Base64.encodeToString((user + ":" + pwd).getBytes(), Base64.NO_WRAP));
或者如果您的令牌包含user和pwd,那么请尝试:
String token = "[your token here]";
toesGet.addHeader("Authorization", "Basic " + Base64.encodeToString(token.getBytes(), Base64.NO_WRAP));
答案 1 :(得分:1)
我没有使用过Apache HttpComponents,但我的理解是你必须为特定主机设置凭据:
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
HttpHost proxy = new HttpHost("proxy.com", 8080, "http");
credentialsProvider.setCredentials(new AuthScope(proxy),
new UsernamePasswordCredentials("usrname", "passwrd"));
credentialsProvider.setCredentials(new AuthScope("api.com", AuthScope.ANY_PORT),
new UsernamePasswordCredentials("apiuser", "apipassword"));
注意:实际上不要键入" apiuser"或" apipassword"在你的代码中。我只将它们显示为占位符。用正确的用户和密码替换它们以访问api.com。 (我指出这一点,因为根据你问题中的代码,我不确定你是否理解你不应该使用文字字符串"[your token here]"
。)