我需要访问一个像这样工作的 API:
curl https://api.com/ratings/v1/ -u [your token here]:
token 是应该传递给 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
对象设置代理,并使用 传递用于代理身份验证的凭据 <以下代码行中的 code>credentialsProvider
:
HttpHost proxy = new HttpHost("proxy.com", 8080, "http");
HttpClient httpClient = HttpClients.custom().setProxy(proxy).setDefaultCredentialsProvider(credentialsProvider).build();
我通过添加 header
将 username
传递给 HttpGet
,如下所示:
toesGet.addHeader("Username", "[your token here]");
当我运行代码时,我得到了这个响应:HTTP/1.1 401 UNAUTHORIZED
这表明我没有以正确的方式将 username
传递给 HttpGet
请求(或者这是否意味着其他含义?)。那么将用户名传递给 get 请求的正确方法是什么?
如有任何帮助,我们将不胜感激,谢谢!
注意:我在credentialsProvider中设置的usrname
和passwrd
是为了代理认证。它们与 HttpGet 请求本身无关。我需要传递的 token 与凭据中提供的 usrname
不同。
最佳答案
我想,您的服务器使用基本身份验证,那么您需要添加“授权” header 而不是“用户名”:
String user = "[your token here]";
String pwd = ""; // blank
toesGet.addHeader("Authorization", "Basic " + Base64.encodeToString((user + ":" + pwd).getBytes(), Base64.NO_WRAP));
或者如果你的 token 包含用户和密码,那么就这样尝试:
String token = "[your token here]";
toesGet.addHeader("Authorization", "Basic " + Base64.encodeToString(token.getBytes(), Base64.NO_WRAP));
关于java - 将用户名传递给 HttpGet 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45308051/