无法找出我在这里做错了什么。尝试在硒测试(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
最佳答案
没有正确编码我的表单值。通过执行类似以下操作来修复:
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"));