【发布时间】: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