【发布时间】:2016-12-17 10:22:23
【问题描述】:
我正在尝试通过 OAuth 连接到 salesforce 生产帐户,并通过提供刷新令牌来交换访问令牌。
当我使用 Chrome Advanced Rest Client 或 CURL 拨打电话时,我可以获得访问令牌;但是当我尝试使用 java HttpClient 或 URLConnection 进行相同的调用时,我得到了 400 状态。
String url = "https://login.salesforce.com/services/oauth2/token";
String requestBody = "grant_type=refresh_token&client_id=myClientId&client_secret=myClientSecret&refresh_token=myRefreshToken";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "myapp/1.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(requestBody);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + requestBody);
System.out.println("Response Code : " + responseCode);
BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
//print result
System.out.println(response.toString());
我使用wireshark 检查了这两个请求。两个请求看起来都一样。由于 URL 是 https,我将请求发布到一个虚拟 URL 并使用wireshark 进行验证。
有人遇到过这种问题吗?顺便说一句,相同的代码适用于开发版,不适用于生产版。对于生产版,它适用于 CURL 和 Chrome ARC。
【问题讨论】:
-
您是否尝试过发布与其他网站的连接?我认为在读取响应之前不关闭 DataOutputStream (wr) 可能是一个问题,尤其是在请求中未发送 Content-Length 标头时。这里有一个发送post请求的示例代码mkyong.com/java/how-to-send-http-request-getpost-in-java
-
是的,几乎一样。即使关闭它仍然是同样的问题。也更新了问题中的代码。
标签: java ssl oauth salesforce httpclient