为什么带有令牌的Java HTTP请求总是未授权的

时间:2019-03-18 15:24:48

标签: java http authentication request

我尝试了以下代码。基本上,此代码取自here。 他在那里声称对他有效。但这对我没有用。

private void doHttp() {
    try {
        String url = "http://myurl.com/cc/companies/3.88";
        String token = "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiZGlyIn0.....";
        URL object = new URL(url);
        HttpURLConnection con = (HttpURLConnection) object.openConnection();
        con.setDoInput(true);
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestProperty("Authorization:", "Token " + token);


        StringBuilder sb = new StringBuilder();
        int HttpResult = con.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), "utf-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
        } else {
            System.out.println(con.getResponseMessage());
        }
    } catch (NotFoundException e) {
        if (e.getResponse().getStatus() == 404) {
            System.out.printf(e.getMessage());
        } else {
            System.out.printf(e.getMessage());
        }
    } catch (WebApplicationException e) {
        System.out.printf(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        System.out.printf(e.getMessage());
    }

它总是失败,并在消息头字段中显示异常消息非法字符:授权:

我尝试了来自终端的相同请求,作为curl -X GET http://myurl.com/cc/companies/3.88 -H“ accept:application / json” -H“ X-Access-Token:eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2 ...” 这很好。

那么我该如何从Java代码中做到这一点呢?

更新的问题

在JB Nizet发表评论之后,我设法使GET和DELETE请求正常运行。但是现在我也想尝试POST。问题再次出现在curl中,因为:-

curl -X POST "http://myurl/app/operator" -H "accept: application/json" -H "X-Access-Token: eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiZGlyIn0..GZ-7sXRhKYHFPKBd.a7tQ2aTYqaKyCp-"  **-H "Content-Type: application/json" -d** "{ \"type\": \"OPERATOR\", \"dcpId\": 42968, \"externalId\": null, \"secondaryExternalId\": null, \"name\": \"Connexion\", \"configurationStage\": \"ACTIVE\", \"nodeStatus\": \"SUCCESS\", \"nodeUser\": null, \"serviceRequest\": null, \"additionalInfo\": null, \"serviceId\": null, \"operatorNo\": null, \"operator\": { \"dcpId\": null, \"name\": null, \"operatorNo\": null}"    

我不知道如何设置正文或-d“ {\” type \“:\” OPERATOR \“,\” dcpId \“:42968,\” externalId \“:空,\” secondaryExternalId \ “:null,\” name \“:\” Connexion \“,\” configurationSt .......}通过Java代码。

我找不到与此相关的API文档。请让我知道如何用Java做到这一点。提前致谢!

0 个答案:

没有答案