Hi
I have written a sample code in java to make a persistent connection to Salesforce's Rest API, This example uses Oauth Grant_Type ="password" to provide a fresh access_token each time the request is made.
Please find the code below. To make this code work you need to add package <httpcomponents-client> to your classpath. which can easily be downloaded from http://hc.apache.org/httpcomponents-client-ga/
Please find the code :
package connection;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONValue;
public class OauthConnection {
//Variables to be populated after gaining the Access token.
private String accessToken = null;
private Map<String, String> oauthLoginResponse;
//Constants to be used in this class.
private static final String clientId = <Your Client ID>;
private static final String clientSecret = <Your Client Secret>;
private static final String environment = "<SalesForce Instance>";
private static final String authUrl = "/services/oauth2/token";
private static final String restUrl = "/services/data/v25.0/";
private static final String queryUrl = "/services/data/v25.0/query";
private static final String username = "<Your SFDC USER NAME>";
private static final String password = <SFDC PASSWORD WITH SECURITY TOKEN>;
public static void main(String[] args){
try{
OauthConnection oc = new OauthConnection();
oc.oAuthSessionProvider();
oc.executeQuery();
}catch(Exception e){
e.printStackTrace();
}
}
public void oAuthSessionProvider()
throws HttpException, IOException
{
// Set up an HTTP client that makes a connection to REST API.
DefaultHttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);
// Set the SID.
System.out.println("Logging in as " + username + " in environment " + environment);
String baseUrl = environment + authUrl;
// Send a post request to the OAuth URL.
HttpPost oauthPost = new HttpPost(baseUrl);
// The request body must contain these 5 values.
List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
parametersBody.add(new BasicNameValuePair("grant_type", "password"));
parametersBody.add(new BasicNameValuePair("username", username));
parametersBody.add(new BasicNameValuePair("password", password));
parametersBody.add(new BasicNameValuePair("client_id", clientId));
parametersBody.add(new BasicNameValuePair("client_secret", clientSecret));
oauthPost.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
// Execute the request.
System.out.println("POST " + baseUrl + "...\n");
HttpResponse response = client.execute(oauthPost);
int code = response.getStatusLine().getStatusCode();
System.out.println("Code >> " +code);
//populate Response map to fetch ACCESS TOKEN for any future call.
this.oauthLoginResponse = (Map<String, String>)JSONValue.parse(EntityUtils.toString(response.getEntity()));
System.out.println("OAuth login response");
for (Map.Entry<String, String> entry : oauthLoginResponse.entrySet())
{
System.out.println(String.format(" %s = %s", entry.getKey(), entry.getValue()));
}
//Populate Access Token
this.accessToken = oauthLoginResponse.get("access_token");
System.out.println("");
}
public void executeQuery(){
DefaultHttpClient httpClient = new DefaultHttpClient();
List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
qsList.add(new BasicNameValuePair("q", "Select a.ParentId, a.OwnerId, a.Name, a.IsPrivate, a.Id, a.Description, a.ContentType, a.BodyLength, a.Body " +
" From Attachment a where a.ParentId = '00390000006DEGb'"));
String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
HttpGet get = new HttpGet(environment + queryUrl+"?"+queryString);
get.setHeader("Authorization", "OAuth " + accessToken);
try{
HttpResponse queryResponse = httpClient.execute(get);
System.out.println(queryResponse.getStatusLine().getReasonPhrase());
Map<String, Object> querynfo = (Map<String, Object>)
JSONValue.parse(EntityUtils.toString(queryResponse.getEntity()));
System.out.println("Query response");
for (Map.Entry<String, Object> entry : querynfo.entrySet())
{
System.out.println(String.format(" %s = %s", entry.getKey(), entry.getValue()));
}
System.out.println("");
}catch(Exception e){
e.printStackTrace();
}
}
}
I have written a sample code in java to make a persistent connection to Salesforce's Rest API, This example uses Oauth Grant_Type ="password" to provide a fresh access_token each time the request is made.
Please find the code below. To make this code work you need to add package <httpcomponents-client> to your classpath. which can easily be downloaded from http://hc.apache.org/httpcomponents-client-ga/
Please find the code :
package connection;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONValue;
public class OauthConnection {
//Variables to be populated after gaining the Access token.
private String accessToken = null;
private Map<String, String> oauthLoginResponse;
//Constants to be used in this class.
private static final String clientId = <Your Client ID>;
private static final String clientSecret = <Your Client Secret>;
private static final String environment = "<SalesForce Instance>";
private static final String authUrl = "/services/oauth2/token";
private static final String restUrl = "/services/data/v25.0/";
private static final String queryUrl = "/services/data/v25.0/query";
private static final String username = "<Your SFDC USER NAME>";
private static final String password = <SFDC PASSWORD WITH SECURITY TOKEN>;
public static void main(String[] args){
try{
OauthConnection oc = new OauthConnection();
oc.oAuthSessionProvider();
oc.executeQuery();
}catch(Exception e){
e.printStackTrace();
}
}
public void oAuthSessionProvider()
throws HttpException, IOException
{
// Set up an HTTP client that makes a connection to REST API.
DefaultHttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);
// Set the SID.
System.out.println("Logging in as " + username + " in environment " + environment);
String baseUrl = environment + authUrl;
// Send a post request to the OAuth URL.
HttpPost oauthPost = new HttpPost(baseUrl);
// The request body must contain these 5 values.
List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
parametersBody.add(new BasicNameValuePair("grant_type", "password"));
parametersBody.add(new BasicNameValuePair("username", username));
parametersBody.add(new BasicNameValuePair("password", password));
parametersBody.add(new BasicNameValuePair("client_id", clientId));
parametersBody.add(new BasicNameValuePair("client_secret", clientSecret));
oauthPost.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
// Execute the request.
System.out.println("POST " + baseUrl + "...\n");
HttpResponse response = client.execute(oauthPost);
int code = response.getStatusLine().getStatusCode();
System.out.println("Code >> " +code);
//populate Response map to fetch ACCESS TOKEN for any future call.
this.oauthLoginResponse = (Map<String, String>)JSONValue.parse(EntityUtils.toString(response.getEntity()));
System.out.println("OAuth login response");
for (Map.Entry<String, String> entry : oauthLoginResponse.entrySet())
{
System.out.println(String.format(" %s = %s", entry.getKey(), entry.getValue()));
}
//Populate Access Token
this.accessToken = oauthLoginResponse.get("access_token");
System.out.println("");
}
public void executeQuery(){
DefaultHttpClient httpClient = new DefaultHttpClient();
List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
qsList.add(new BasicNameValuePair("q", "Select a.ParentId, a.OwnerId, a.Name, a.IsPrivate, a.Id, a.Description, a.ContentType, a.BodyLength, a.Body " +
" From Attachment a where a.ParentId = '00390000006DEGb'"));
String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
HttpGet get = new HttpGet(environment + queryUrl+"?"+queryString);
get.setHeader("Authorization", "OAuth " + accessToken);
try{
HttpResponse queryResponse = httpClient.execute(get);
System.out.println(queryResponse.getStatusLine().getReasonPhrase());
Map<String, Object> querynfo = (Map<String, Object>)
JSONValue.parse(EntityUtils.toString(queryResponse.getEntity()));
System.out.println("Query response");
for (Map.Entry<String, Object> entry : querynfo.entrySet())
{
System.out.println(String.format(" %s = %s", entry.getKey(), entry.getValue()));
}
System.out.println("");
}catch(Exception e){
e.printStackTrace();
}
}
}
Hello and thank you for your sample. I am confused about one thing though. In order to get a client id and a client secret from salesforce (in remote client definition) I have to supply a callback url. Did you have to do this? This is POJO, right? No app server involved?
ReplyDeleteThanks -- I hope you are still out there and can provide some insight!
Yes Stephen, this is a simple POJO no app server is required, and yes I did supply a callback url and which could be anything :) I just passed www.google.com ..
DeleteSeems to not matter what I supplied in the callback url. I just specified a dummy url. I got my java program working and pulling records form salesforce. Thanks! Your post did it for me!
ReplyDeleteI'm just trying to compile:
ReplyDeletejavac -cp /home/mvora/Desktop/httpcomponents-client-4.2.5/lib/httpclient-4.2.5.jar:/home/mvora/Desktop/httpcomponents-client-4.2.5/lib/httpclient-cache-4.2.5.jar:/home/mvora/Desktop/httpcomponents-client-4.2.5/lib/httpcore-4.2.4.jar:/home/mvora/Desktop/httpcomponents-client-4.2.5/lib/httpmime-4.2.5.jar:/home/mvora/Desktop/httpcomponents-client-4.2.5/lib/commons-codec-1.6.jar:/home/mvora/Desktop/httpcomponents-client-4.2.5/lib/commons-logging-1.1.1.jar:/home/mvora/Desktop/httpcomponents-client-4.2.5/lib/fluent-hc-4.2.5.jar:/home/mvora/Desktop/json-simple-1.1.1.jar OauthConnection.java
Note: OauthConnection.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: OauthConnection.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
and then run
java -cp /home/mvora/Desktop/httpcomponents-client-4.2.5/lib/httpclient-4.2.5.jar:/home/mvora/Desktop/httpcomponents-client-4.2.5/lib/httpclient-cache-4.2.5.jar:/home/mvora/Desktop/httpcomponents-client-4.2.5/lib/httpcore-4.2.4.jar:/home/mvora/Desktop/httpcomponents-client-4.2.5/lib/httpmime-4.2.5.jar:/home/mvora/Desktop/httpcomponents-client-4.2.5/lib/commons-codec-1.6.jar:/home/mvora/Desktop/httpcomponents-client-4.2.5/lib/commons-logging-1.1.1.jar:/home/mvora/Desktop/httpcomponents-client-4.2.5/lib/fluent-hc-4.2.5.jar:/home/mvora/Desktop/json-simple-1.1.1.jar OauthConnection
Error: Could not find or load main class OauthConnection
Do you know what's wrong?
This is what I get.
ReplyDeleteOauthConnection.java:81: warning: [deprecation] UTF_8 in HTTP has been deprecated
oauthPost.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
^
OauthConnection.java:113: warning: [deprecation] UTF_8 in HTTP has been deprecated
String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
^
Note: OauthConnection.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 warnings
What should I do?