我使用NiFi的InvokeHTTP處理器張貼到Salesforce的端點,特別是對登錄端點都:HttpClient的POST JSON的身體和網址參數
https://test.salesforce.com/services/oauth2/token
我追加CLIENT_ID,client_secret,用戶名和密碼字段的網址:
https://test.salesforce.com/services/oauth2/token?grant_type=password&client_id=<client_id>&client_secret=<client_secret>&username=<username>&password=<password + key>
並且除了有一個JSON消息/有效載荷,通過InvokeHTTP處理器傳遞,所以我配置
Content-Type: application/json
而且這個工作正常,當我運行它。
[注意:那些不瞭解Apache NiFi但知道Java和/或SFDC中的HttpClient的人可以回答這個問題,我的觀點是在NiFi上REST API端點適用於我,但當我試圖達到使用自定義的Java代碼]
現在,是因爲我想這個機制轉換爲ExecuteScript處理器的自定義代碼的REST API,我嘗試使用HttpClient庫在Java編碼。但似乎有這樣做的多種方式,根據這篇文章Baeldung。我想第4項第一:
CloseableHttpClient client = HttpClients.createDefault();
String urlStr = "https://test.salesforce.com/services/oauth2/token?grant_type=password&client_id=<client_id>&client_secret=<client_secret>&username=<username>&password=<password + key>";
HttpPost httpPost = new HttpPost(urlStr);
String jsonPayload = "{\"qty\":100,\"name\":\"iPad 4\"}";
StringEntity entity = new StringEntity(jsonPayload);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
System.out.println(response.getStatusLine().getStatusCode());
InputStream is = response.getEntity().getContent();
String responseStr = IOUtils.toString(is, "UTF-8");
System.out.println(responseStr);
client.close();
在我得到:
400
{"error":"invalid_grant","error_description":"authentication failure"}
我也嘗試在網頁中第2項模式,沒有JSON有效載荷,作爲參數將是我的實體現在:
CloseableHttpClient client = HttpClients.createDefault();
String urlStr = "https://test.salesforce.com/services/oauth2/token";
HttpPost httpPost = new HttpPost(urlStr);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("grant_type", "password"));
params.add(new BasicNameValuePair("client_id", CLIENT_ID));
params.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
params.add(new BasicNameValuePair("username", USERNAME));
params.add(new BasicNameValuePair("password", PASSWORD));
httpPost.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response = client.execute(httpPost);
System.out.println(response.getStatusLine().getStatusCode());
InputStream is = response.getEntity().getContent();
String responseStr = IOUtils.toString(is, "UTF-8");
System.out.println(responseStr);
client.close();
在這種情況下,我也得到相同的迴應。我在Java代碼中丟失了什麼?如何結合兩種模式,與params
和jsonPayload
爲實體?
不應該使用'URIBuilder'和'HttpGet'呢? – lonesome
@lonesome也許這就是我應該使用的。感謝提示。 – menorah84
,如果你認爲這將是有幫助的,我可以張貼與一個類似的案件代碼的答案(bing搜索API)。 – lonesome