英文:
Adding an authentication token to header in Restlet
问题
以下是您要翻译的内容:
我正在尝试使用Java中的Restlet进行API调用,但当我运行我的代码时,我收到一个org.restlet.resource.ResourceException:未经授权(401)- 该请求需要用户身份验证。
API调用的格式如下(对于shell):curl "<api_url>" \ -H "Authorization: Bearer <api_token_here>"
然而,我不确定如何在Restlet中添加此授权标头,因为您无法使用.getRequest().getHeaders().add();
来添加标头。
此外,我已经尝试设置挑战响应,但这似乎也不起作用。
API = new ClientResource(RequestURL);
API.setProtocol(Protocol.HTTPS);
ChallengeResponse AuthHeader = new ChallengeResponse(ChallengeScheme.CUSTOM);
AuthHeader.setRawValue("Authorization: Bearer " + APIKey);
API.getRequest().setChallengeResponse(AuthHeader);
API.get();
英文:
I am trying to make an API call using Restlet in java however when I run my code I get an org.restlet.resource.ResourceException: Unauthorized (401) - The request requires user authentication
The format for the API call is as follows for shell: curl "<api_url>" \
-H "Authorization: Bearer <api_token_here>"
However I am unsure how to add this authorization header in Restlet, as you are not able to add the header using .getRequest().getHeaders().add();
Additionally I have tried to set a challenge response however this also does not appear to work.
API = new ClientResource(RequestURL);
API.setProtocol(Protocol.HTTPS);
ChallengeResponse AuthHeader = new ChallengeResponse(ChallengeScheme.CUSTOM);
AuthHeader.setRawValue("Authorization: Bearer " + APIKey);
API.getRequest().setChallengeResponse(AuthHeader);
API.get();
答案1
得分: 0
我似乎已经通过以下代码解决了这个问题:
ChallengeResponse AuthHeader = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
AuthHeader.setRawValue(APIKey);
AuthHeader.setIdentifier("Bearer");
API.setChallengeResponse(AuthHeader);
英文:
I appear to have solved the issue with the following code:
ChallengeResponse AuthHeader = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
AuthHeader.setRawValue(APIKey);
AuthHeader.setIdentifier("Bearer");
API.setChallengeResponse(AuthHeader);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论