Invoking Salesforce REST based web service from Java
This post will explain the approach to call the Salesfore REST based webservice through java.I have exposed a Apex class as REST service from salesforce to fetch the account details.
@RestResource(urlMapping='/AccountDetails/*')
global with sharing class AccountDetails {
@HttpGet
global static Account doGet() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
System.debug('Account Id:'+accountId);
Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId];
return result;
}
}
- getting the access_token
- invoking the service endpoint by attaching the access_token to the request.
import java.io.*;
import java.net.*;
import org.w3c.dom.*;
public class RestCaller {
public static void main(String[] args) throws Exception {
String urlParameters = "grant_type=password&client_id=3MVG9Y6d_xxxxxxxx&client_secret=80xxxxxxxx&username=albinsharpxxxxx&password=xxxxxxxxx";
String loginresponse = RestCaller.execute(
"https://login.salesforce.com/services/oauth2/token", "POST",urlParameters, "application/x-www-form-urlencoded", null);
String sessionId=getSessionId(loginresponse);
String serviceResponse =RestCaller.execute("https://ap1.salesforce.com/services/apexrest/AccountDetails","GET","0019000000AZBCNAA5","application/xml",sessionId);
System.out.println("Service Response \n" + serviceResponse);
}
public static String execute(String targetURL, String HttpMethod,
String urlParameters, String contentType, String SessionId) {
URL url;
HttpURLConnection connection = null;
try {
url = new URL(targetURL);
if (HttpMethod == "GET") {
url = new URL(url.toString() + "/" + urlParameters);
}
connection = (HttpURLConnection) url.openConnection();
if (SessionId != null)
connection.setRequestProperty("Authorization", "OAuth "+ SessionId);
connection.setRequestProperty("accept", "application/xml");
if (HttpMethod == "POST") {
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length","" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(urlParameters);
writer.flush();
writer.close();
os.close();
}
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return (e.getClass().getName());
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
static String getSessionId(String loingResponse)
{
java.io.InputStream sbis = new java.io.StringBufferInputStream(loingResponse.toString());
javax.xml.parsers.DocumentBuilderFactory b = javax.xml.parsers.DocumentBuilderFactory.newInstance();
b.setNamespaceAware(false);
org.w3c.dom.Document doc = null;
javax.xml.parsers.DocumentBuilder db = null;
try {
db = b.newDocumentBuilder();
doc = db.parse(sbis);
} catch (Exception e) {
e.printStackTrace();
}
org.w3c.dom.Element element = doc.getDocumentElement();
String access_token="";
NodeList nodeList = element.getElementsByTagName("access_token");
if(nodeList!=null && nodeList.getLength() > 0){
Element myElement = (Element)nodeList.item(0);
access_token= myElement.getFirstChild().getNodeValue();
}
return access_token;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<response xsi:type="sObject" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<type>Account</type>
<Id>0019000000AZBCNAA5</Id>
<Name>GenePoint</Name>
<Phone>(650) 867-3450</Phone>
<Website>www.genepoint.com</Website>
</response>
hey,
ReplyDeleteI am trying to do the same but getting connection time out. Is there anything to modify from sfdc end? Please help.
Possible your have proxy that blocking the access.
DeleteYou should add in your java code:
System.getProperties().put("https.proxyHost", {Proxy Host});
System.getProperties().put("https.proxyPort", {Proxy Port});
System.getProperties().put("https.proxyUser", {User Name});
System.getProperties().put("https.proxyPassword", {Password});