【问题标题】:{"error":"unsupported_grant_type","error_description":"grant type not supported"} SalesForce Java{"error":"unsupported_grant_type","error_description":"授权类型不支持"} SalesForce Java
【发布时间】:2019-08-21 14:35:33
【问题描述】:

无法弄清楚我在这里做错了什么。尝试在硒测试(java)中通过 SF 的 API 获取访问令牌,并不断收到相同的错误。在 cypress (javascript) 中进行了完全相同的调用,它工作得非常好,但是,由于其他原因,我不能走这条路(SF 讨厌 UI 测试)。我认为这可能与它必须是表单数据这一事实有关,而 java 对此很奇怪? idk,请帮忙,我很害怕。

已经尝试将请求正文设置为一个长字符串,而不是将所有内容都添加到JSONObject,但这仍然不起作用

        URL obj = new URL("https://login.salesforce.com/services/oauth2/token");
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        JSONObject body = new JSONObject();
        body.put("grant_type", "password");
        body.put("client_id", "***");
        body.put("client_secret", "***");
        body.put("username", "tyler+prod@pactsafe.com");
        body.put("password", "***");
//        String jsonInputString = "{ grant_type: 'password', client_id: '***', client_secret: '***', password: '***', username: 'tyler+prod@pactsafe.com'";

        System.out.println(body.toString());

        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
        wr.write(body.toString());
        wr.flush();

        int httpResult = con.getResponseCode();
        InputStream inputStream;
        if (200 <= httpResult && httpResult <= 299) {
            inputStream = con.getInputStream();
        } else {
            inputStream = con.getErrorStream();
        }

        BufferedReader in = new BufferedReader(
                new InputStreamReader(inputStream));

        StringBuilder response = new StringBuilder();
        String currentLine;

        while ((currentLine = in.readLine()) != null)
            response.append(currentLine);

        in.close();


        System.out.println(response.toString());
        System.out.println(httpResult);

        driver.get("https://na85.lightning.force.com/lightning/setup/SetupOneHome/home");

我明白了:

{"password":"***","grant_type":"password","client_secret":"***","client_id":"***","username":"tyler+prod@pactsafe.com"}
{"error":"unsupported_grant_type","error_description":"grant type not supported"}
400

【问题讨论】:

  • 别害怕,一切都会好起来的。 :) 不确定细节,但我认为您可能需要使用HttpClient 和FormUrlEncodedContent。从示例here 中窃取。特别是第 3 步
  • @mrfreester 不是 c# 吗?
  • 哎呀...是的,抱歉,我打开了几篇帖子并混淆了语言...
  • 哈哈不用担心,谢谢!你至少在正确的轨道上 - 我没有正确编码我的表单值

标签: java api selenium httpurlconnection salesforce-lightning


【解决方案1】:

没有正确编码我的表单值。通过做类似的事情来修复:

StringBuilder sb = new StringBuilder("grant_type=password");
sb.append("&client_id=").append(URLEncoder.encode("client_id__shhhh, "UTF-8"));
sb.append("&client_secret=").append(URLEncoder.encode("secret shhhhh", "UTF-8"));

【讨论】:

    【解决方案2】:

    以下答案非常具有误导性,不知道 Tyler 修复了什么,他应该有礼貌地发布他的工作代码。

    当我使用 RestTemplate 并且大多数使用 MultiValueMap for x-www-form-urlencoded body 的答案会在 Salesforce {“error” :“unsupported_grant_type”,“error_description”:“授权类型不支持”}。

    我终于通过反复试验找到了解决方案。下面的代码就像一个魅力!

    我正在使用一个 Rest Template 来实现这一点:

    public String getAccessTokenBody() throws Exception {
        
        try
        {
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/x-www-form-urlencoded");
            
            UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.newInstance().host("YOUR-INSTANCE.my.salesforce.com").scheme("https").pathSegment("services/oauth2/token")
                    .queryParam("grant_type", "password")
                    .queryParam("client_id", "your client id")
                    .queryParam("client_secret", "your client secret")
                    .queryParam("username", "your user name")
                    .queryParam("password", "your password");
            HttpEntity requestEntity = new HttpEntity<>(headers);
            ResponseEntity<String> response = restTemplate.postForEntity(uriComponentsBuilder.build().toString().trim(), requestEntity, String.class);
            return response.getBody();
            
        }catch (HttpClientErrorException httpClientErrorException){
            ResponseEntity<String> responseEntity = new ResponseEntity<>(httpClientErrorException.getResponseBodyAsString(), httpClientErrorException.getStatusCode());
            throw new Exception(responseEntity.getBody());
        }
        catch (HttpStatusCodeException httpStatusCodeException) {
            ResponseEntity<String> responseEntity = new ResponseEntity<>(httpStatusCodeException.getResponseBodyAsString(), httpStatusCodeException.getStatusCode());
            throw new Exception(responseEntity.getBody());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 2017-05-14
      • 2017-09-18
      • 1970-01-01
      相关资源
      最近更新 更多