如何在JAVA中使用OAuth 2.0获取/发布资源(状态代码415)

时间:2019-07-04 08:51:23

标签: java rest api http shopware

我有一个用Java实现oauth 2.0的实现,我想尝试使用Shopware 6 API进行一些尝试。我可以毫无问题地获得访问令牌,据我所知,我正在尽一切努力使用此access_token请求资源。在GET Request的标头中,放置了“ Authorization Bearer” + access_token标头以及“ Content-Type”,“ application / json”标头。

HttpGet get = new HttpGet(resourceURL);
        get.addHeader("Content-Type", "application/json");

及以后

if (isValid(accessToken)) {
                        // update the access token
                        // System.out.println("New access token: " + accessToken);
                        oauthDetails.setAccessToken(accessToken);
                        // remove the old auth header
                        get.removeHeaders(OAuthConstants.AUTHORIZATION);
                        // add the new auth header
                        get.addHeader(OAuthConstants.AUTHORIZATION,
                                getAuthorizationHeaderForAccessToken(oauthDetails.getAccessToken()));
                        get.releaseConnection();
                        response = client.execute(get);
                        code = response.getStatusLine().getStatusCode();

我总是得到的错误代码是415。 这是完整的响应:

HttpResponseProxy{HTTP/1.1 415 Unsupported Media Type [Date: Thu, 04 Jul 2019 08:45:38 GMT, Server: Apache/2.4.25 (Debian), Cache-Control: no-cache, private, Access-Control-Allow-Origin: *, Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE, Access-Control-Allow-Headers: Content-Type,Authorization,sw-context-token,sw-access-key,sw-language-id,sw-version-id, sw-version-id: , sw-language-id: , sw-context-token: , x-frame-options: deny, X-Debug-Token: c1766c, X-Debug-Token-Link: http://localhost:8000/_profiler/c1766c, X-Robots-Tag: noindex, Vary: Authorization, Keep-Alive: timeout=5, max=100, Connection: Keep-Alive, Transfer-Encoding: chunked, Content-Type: application/json] ResponseEntityProxy{[Content-Type: application/json,Chunked: true]}}

我试图获取的端点是“ http://localhost:8000/api/v1/category/”端点。如果我用失眠/邮递员做这件事,我会得到预期的类别信息。 有人知道什么地方可能出问题吗?我在这里想念什么?

2 个答案:

答案 0 :(得分:0)

请添加以下标题

'Accept': 'application/json'

答案 1 :(得分:0)

正如nuriselcuk在评论中指出的那样,缺少的东西是Accept标头。 我添加了

post.addHeader("Accept", "application/json");

现在可以正常工作了。