0

这是我第一个使用 Java、Spring Boot 和 Maven 的应用程序 Allegro Rest api。我正在尝试使用本指南https://developer.allegro.pl/auth/#clientCredentialsFlow进行授权 Client_credentials 流程并调用 REST API 资源。但是结果我有错误:422 Unprocessable Entity。我应该怎么办?

`

      @Autowired
     RestTemplate restTemplate;

      private static final String clientId = "...";
      private static final String clientSecret = "...";
      private String URL= "https://allegro.pl/auth/oauth/token?grant_type=client_credentials";
      private static final String ACCEPT_HEADER = "application/vnd.allegro.public.v1+json";

 @RequestMapping(value = "/auth2", method = RequestMethod.GET)
 public String showEmployees() throws JsonProcessingException, IOException
 {
    try {
        String auth = clientId + ":" + clientSecret;
        byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.add("Authorization", authHeader);
        HttpEntity<String> request = new HttpEntity<String>(headers);
        System.out.println(authHeader);
        String response2 = restTemplate.exchange(URL, HttpMethod.POST, request, String.class).getBody();

        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(response2);
        String token = node.path("access_token").asText();
        System.out.println(token);
        String url2 = "https://api.allegro.pl/offers/listing";

        HttpHeaders headers1 = new HttpHeaders();
        headers1.add("Accept", ACCEPT_HEADER);
        headers1.add("Content-type", "application/vnd.allegro.beta.v1+json");
        headers1.add("Authorization", "Bearer " + token);
        HttpEntity<String> entity = new HttpEntity<String>(headers1);
        String responseEntity = restTemplate.exchange(url2, HttpMethod.GET, entity, String.class).getBody();
        return responseEntity;
    }
    catch (JsonProcessingException e)
    {
        throw new RuntimeException(e);
    }
 }

`

4

0 回答 0