在Java程序中调用Salesforce REST API

Salesforce 提供多种不同的REST API接口以支持客户应用的开发,本文介绍如何在Java程序中使用Apache HttpComponents调用Salesforce REST API。


第一步: 登录Salesforce


首先设置包括Salesforce登录主机和 登录接口URL, 并初始化一个Post请求。

	HttpHost target = new HttpHost("login.salesforce.com", 443, "https");

	String loginURL= "/services/Soap/u/29.0";

	HttpPost loginPost = new HttpPost(loginURL);


然后设置Post头信息

	loginPost.setHeader("content-type", "text/xml"); 
	loginPost.setHeader("charset", "UTF-8"); 
	loginPost.setHeader("SOAPAction", "login");  


其后发送一个Post登录请求并接受其响应。

	String loginRequestXMLTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + 
					"<env:Envelope\n" +
					"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" + 
					"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + 
					"xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + 
					"<env:Body>\n" + 
					"   <n1:login xmlns:n1=\"urn:partner.soap.sforce.com\">\n" +
					"       <n1:username>%s</n1:username>\n" + 
					"       <n1:password>%s%s</n1:password>\n" + 
					"</n1:login>\n" + 
					"</env:Body>\n" + 
					"</env:Envelope>\n";

	String loginRequestXML = String.format(loginRequestXMLTemplate, _username, _password, _securityToken);

	System.out.println("Request...");
	System.out.println(loginRequestXML);

	StringEntity input = new StringEntity(loginRequestXML);
	loginPost.setEntity(input);

	CloseableHttpResponse loginResponse = httpClient.execute(target, loginPost);

	HttpEntity entity = loginResponse.getEntity();

	String response = EntityUtils.toString(entity);

	EntityUtils.consume(loginResponse.getEntity());
	loginResponse.close();


获取登录响应之后将其转换为XML结构,并读取sessionId和serverUrl

	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder = factory.newDocumentBuilder();
	Document document = builder.parse(new InputSource(new StringReader(response)));

	Node node = document.getElementsByTagName("sessionId").item(0);
	sessionId = node.getFirstChild().getTextContent();

	node = document.getElementsByTagName("serverUrl").item(0);
	String serverUrlString = node.getFirstChild().getTextContent();
	serverURL = new URL (serverUrlString);

第二步: 调用List Report REST API


首先设置REST AP接口主机和 List Report REST AP接口URL, 并初始化一个Get请求。
	target = new HttpHost(serverURL.getHost(), 443, "https");
	String listReportURL= "/services/data/v29.0/analytics/reports/";
	HttpGet reportListGet = new HttpGet(listReportURL);


然后设置Get头信息

	reportListGet.setHeader("Authorization", "Bearer " + sessionId);


其后发送Get请求并接受其响应

	CloseableHttpResponse reportListResponse = httpClient.execute(target, reportListGet); 
	entity = reportListResponse.getEntity(); 
	response = EntityUtils.toString(entity);
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页