请求中缺少令牌

时间:2019-03-07 09:53:12

标签: java json rest header token

在这里,我尝试将生成的令牌与数据一起从标头发送到API,但出现错误:

  

请求中缺少令牌

不确定我的代码有什么问题,有人可以指导我解决此问题,谢谢。

String url = "API_TO_GENERATE_TOKEN"; 
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.set("Content-Type", "application/json");
                httpHeaders.set("CLIENT_ID", "VALUE_OF_CLIENTID");
                httpHeaders.set("CLIENT_SECRET", "VALUE_OF_CLIENT_SECRET");
                JSONObject json = new JSONObject();
                HttpEntity <String> httpEntity = new HttpEntity <String> (json.toString(), httpHeaders);
                RestTemplate restTemplate = new RestTemplate();
                String response = restTemplate.postForObject(url, httpEntity, String.class);
                JSONObject jsonObj = new JSONObject(response);
                System.out.println("Json Obj is:"+jsonObj);
                /*String balance = jsonObj.get("data").toString();
                System.out.println("Response is:"+response);*/
                JSONObject jsonObj1 = jsonObj.getJSONObject("data");
                String token = jsonObj1.getString("token");
                System.out.println("Token is " + token);        

                String url1=API_TO_ADD_USER";
                HttpHeaders httpHeaders1=new HttpHeaders();
                httpHeaders1.set("CLIENT_ID", "VALUE_OF_CLIENT_ID");
                httpHeaders1.set("CLIENT_SECRET", "VALUE_OF_CLIENT_SECRET");
                httpHeaders1.set("Content-Type","application/json");
                httpHeaders1.set("Authorization","Bearer"+token);

//              JSONObject json1 = new JSONObject();

                Filter u= new Filter();


                u.setName("my_name");
                u.setPhone("123456789");
                u.setVendorId("P1234");
                u.setAddress1("my_address1");
                u.setAddress2("my_address2");
                u.setCity("my_city");
                u.setState("my_state");
                u.setEmail("myemail@abc.com");

                HttpEntity<Filter> httpEntity1 = new HttpEntity<>(u, httpHeaders1);
                RestTemplate restTemplate1 = new RestTemplate();
                //String response1 = restTemplate1.postForObject(url1, httpEntity1, String.class);

                ResponseEntity<String> response1 = restTemplate.postForEntity(url1, httpEntity1, String.class);

//              JSONObject jsonObj2 = new JSONObject(response1);
                System.out.println("Json Obj111 is:"+response1);

1 个答案:

答案 0 :(得分:0)

在使用RestClient时,我遇到了类似的问题,因为没有用空格分隔“承载者”和令牌,所以我会去httpHeaders1.set("Authorization","Bearer "+token),就可以了。