在这里,我试图将生成的令牌从标头与数据一起发送到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("[email protected]");
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);
最佳答案
我在使用RestClient时遇到了类似的问题,因为不使用空格分隔“ Bearer”和令牌,所以我会选择httpHeaders1.set("Authorization","Bearer "+token)
,您应该会很好。