Hi Precision Marketing Dev community,
in this tutorial i'm going to share with you a Java sample code that will help you build your calls to the Precision Marketing Device API.
we will connect to the SPM Trial data set (New York Grocery) and retrieve the offers available around a particular place in New York (Latitude=40.774960& Longitude=-73.967755)
If you do not already have your trial credentials, please request a Trial Account from the SPM Developer community page
The Java code below will:
- (1) Register an Anonymous User
- (2) Create a limited session
- (3) Get the Offers
Notes/troubleshooting:
- If you are running this code behind a Proxy you will need to uncomment the ProxySelector section in the code below and enter your proxy settings.
- you will need to load GSON in your Eclipse to run this code, you can get it from here: Downloads - google-gson - A Java library to convert JSON to Java objects and vice-versa - Google Project Hosting
package eclipsePackage; //Demonstrate URLConnection. import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.ProxySelector; import java.net.SocketAddress; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; //import ; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; public class GetOffers { public static void main(String args[]) throws Exception { URL url = null; String urlStr = null; String paramStr = null; String signString = null; // Needless String strCmdUrl = null; String WEB_SERVER = "https://sprdeviceapisstaging.hana.ondemand.com"; String URL_BASE = "/deviceapi/v1/rest"; String DEVELOPER_ID="replace_with_your_developer_id"; String SECRET = "replace_with_your_secret"; // Use this piece of code if you are behind a proxy server. Update the proxy details accordingly // ProxySelector.setDefault(new ProxySelector() { // @Override // public List<Proxy> select(URI uri) { // return Arrays.asList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.wdf.sap.corp", 8080))); // } // @Override // public void connectFailed(URI arg0, SocketAddress arg1, IOException arg2) { // throw new RuntimeException("Proxy connect failed", arg2); // } // }); String urlbaseStr = WEB_SERVER + URL_BASE; //NSData *paramData = nil; String getInterestHeaderStr = null; String getInterestTrailerStr = null; // NSHTTPURLResponse *urlResponse = nil; // NSData *returnData = nil; // NSError *parsingError = nil; // NSDictionary *json = nil; String deviceIdStr = null; String consumerIdStr = null; String sessionIdStr = null; String offerCountStr = null; HttpURLConnection connection = null; PrintWriter pw; JsonParser parser = null; JsonReader reader = null; JsonElement jElement = null; JsonObject jObj = null; Gson gson = new Gson(); // Entry point // RestClient restClient = new RestClient(); // (1) Registration Anonymous User System.out.println("-- (1) -- Anonymous registration"); strCmdUrl = "/registration/device/anonymous?"; urlStr = urlbaseStr + strCmdUrl; System.out.println("URLStr : " + urlStr); url = new URL(urlStr); paramStr = "clientname=iOS-SDK&clientversion=1.0&hardwaremanufacturer=Apple Inc&hardwaremodel=iPhone Simulator&latitude=40.774960&longitude=-73.967755&osname=iPhone OS&osversion=7.0&screenheight=960&screenwidth=640"; connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("developer-id", API_KEY); connection.setRequestProperty("developer-secret", API_SECRET); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8"))); pw.print(paramStr);// content pw.close(); System.out.println("ParamStr : " + paramStr); //Json parser = new JsonParser(); reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); jElement = parser.parse(reader); jObj = jElement.getAsJsonObject(); deviceIdStr = jObj.get("data").getAsJsonObject().get("deviceId").getAsString(); System.out.println("-- Test deviceId-- : " + deviceIdStr); System.out.println(jElement.toString()); reader.close(); System.out.println("-- Header field (0) -- : " + connection.getHeaderField(0)); // connection. connection.disconnect(); // (2) Create limited session System.out.println("-- (2) -- Create limited session"); strCmdUrl = "/sessions/limited?"; urlStr = urlbaseStr + strCmdUrl; System.out.println("URLStr : " + urlStr); url = new URL(urlStr); paramStr = "deviceid=" + deviceIdStr + "&hardwaremanufacturer=Apple Inc&hardwaremodel=iPhone Simulator&latitude=40.774960&locale=en_CA&longitude=-73.967755&osname=iPhone OS&osversion=7.0&screenheight=960&screenwidth=640"; System.out.println("paramStr : " + paramStr); connection = null; connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("developer-id", API_KEY); connection.setRequestProperty("developer-secret", API_SECRET); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8"))); pw.print(paramStr);// content pw.close(); //Json parser = new JsonParser(); reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); jElement = parser.parse(reader); jObj = jElement.getAsJsonObject(); // Pring return System.out.println(jElement.toString()); //Get SessionID and ConsumerID sessionIdStr = jObj.get("data").getAsJsonObject().get("sessionId").getAsString(); consumerIdStr = jObj.get("data").getAsJsonObject().get("consumerId").getAsString(); System.out.println("SessionID : " + sessionIdStr); System.out.println("ConsumerID : " + consumerIdStr); //Get cookies //String cookieStr = connection.getHeaderField("Set-Cookie"); String cookieStr = connection.getHeaderFields().get("Set-Cookie").toString(); String dateStr = connection.getHeaderField("Date"); // PARSING THE COOKIE STRING cookieStr = cookieStr.replace("[", ""); cookieStr = cookieStr.replace("]", ""); cookieStr = cookieStr.replaceAll(",", ";"); StringTokenizer st2 = new StringTokenizer(cookieStr, ";"); ArrayList<String> elements = new ArrayList<String>(); while (st2.hasMoreTokens()) { elements.add(st2.nextToken()); } cookieStr = elements.get(0) + ";" + elements.get(4); // PARSING THE COOKIE STRING System.out.println("-- Cookie obj --" + cookieStr.toString()); reader.close(); connection.disconnect(); // (3) Get offers System.out.println("-- (3) -- Get offers"); getInterestHeaderStr = "/consumers/" + consumerIdStr; getInterestTrailerStr = "/offers?"; // + "JSESSIONID=" + sessionIdStr; strCmdUrl = getInterestHeaderStr + getInterestTrailerStr; paramStr = ""; urlStr = urlbaseStr + strCmdUrl + paramStr; url = new URL(urlStr); System.out.println("URLStr : " + urlStr); System.out.println("paramStr : " + paramStr); connection = null; connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Accept", "*/*"); // connection.setRequestProperty("developer-id", API_KEY); // connection.setRequestProperty("developer-secret", API_SECRET); //Cookie connection.setRequestProperty("Cookie", cookieStr); System.out.println("Cookie Str : " + cookieStr); /* pw = new PrintWriter(new BufferedWriter( new OutputStreamWriter( connection.getOutputStream() ,"utf-8"))); pw.print(paramStr);// content pw.close(); */ //Json parser = new JsonParser(); reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); jElement = parser.parse(reader); jObj = jElement.getAsJsonObject(); // Pring return System.out.println(jElement.toString()); //Get offers offerCountStr = jObj.get("data").getAsJsonObject().get("offerCount").getAsString(); System.out.println("Offer Count : " + offerCountStr); } }
How to get this code to work?
- Create you Java Package and copy/paste the java code.
- replace your developer_ID and secret
- Reference the GSON library in your eclipse
- Check that there are no errors and run the code as Java application
You should get the response below:
-- (1) -- Anonymous registration URLStr : https://sprdeviceapisstaging.hana.ondemand.com/deviceapi/v1/rest/registration/device/anonymous? ParamStr : clientname=iOS-SDK&clientversion=1.0&hardwaremanufacturer=Apple Inc&hardwaremodel=iPhone Simulator&latitude=40.774960&longitude=-73.967755&osname=iPhone OS&osversion=7.0&screenheight=960&screenwidth=640 -- Test deviceId-- : bdbb2ecb-884f-43e2-b221-4b0a313e8104 {"meta":{"returnCode":"OK"},"data":{"deviceId":"bdbb2ecb-884f-43e2-b221-4b0a313e8104"}} -- Header field (0) -- : HTTP/1.1 200 OK -- (2) -- Create limited session URLStr : https://sprdeviceapisstaging.hana.ondemand.com/deviceapi/v1/rest/sessions/limited? paramStr : deviceid=bdbb2ecb-884f-43e2-b221-4b0a313e8104&hardwaremanufacturer=Apple Inc&hardwaremodel=iPhone Simulator&latitude=40.774960&locale=en_CA&longitude=-73.967755&osname=iPhone OS&osversion=7.0&screenheight=960&screenwidth=640 {"meta":{"returnCode":"OK"},"data":{"sessionId":"602dbb01-b0c4-4b44-b232-4b54fa5436eb","consumerId":"76316a0c-e122-49a5-a121-0bb9ff0d286e"}} SessionID : 602dbb01-b0c4-4b44-b232-4b54fa5436eb ConsumerID : 76316a0c-e122-49a5-a121-0bb9ff0d286e -- Cookie obj --BIGipServersprdeviceapisstaging.hana.ondemand.com=!p3IhFJycsnCKoWSi5dnEoFAblcJlCL7x9vkoz5nixz6R0NuUb5Wa5Iig92ahEvyPMORtgCTJ6G1hGQ==; JSESSIONID=2A978C2102E2FC1B4A9332C4E5B83D8F21E6B2016CE85B426D3DB42C71E1FD60 -- (3) -- Get offers URLStr : https://sprdeviceapisstaging.hana.ondemand.com/deviceapi/v1/rest/consumers/76316a0c-e122-49a5-a121-0bb9ff0d286e/offers? paramStr : Cookie Str : BIGipServersprdeviceapisstaging.hana.ondemand.com=!p3IhFJycsnCKoWSi5dnEoFAblcJlCL7x9vkoz5nixz6R0NuUb5Wa5Iig92ahEvyPMORtgCTJ6G1hGQ==; JSESSIONID=2A978C2102E2FC1B4A9332C4E5B83D8F21E6B2016CE85B426D3DB42C71E1FD60 {"meta":{"returnCode":"OK"},"data":{"offerCount":5,"currencySymbol":"$","currencyCode":"USD","totalMoneyValue":10.75,"totalPointsValue":0,"offers":[{"id":"f0e8fb15-7f81-4d76-9618-678544ff8900-87320a30","offerType":"Percentage discount","value":0.10,"storeId":null,"isCashback":false,"isCounter":false,"isFreeItem":false,"isMoney":false,"isPercentage":true,"isPoint":false,"buyQuantity":0,"getQuantity":0,"validFromUtc":"1342328400000","validToUtc":"1405400400000","numberOfProductsInThisOffer":1,"offerProducts":[{"productId":"6051a30d-bf88-4db7-9db5-69874a6aaa2b","productFamily":"Vinegars","brandName":"Shurfine","retailPrice":5.59,"currencySymbol":"$","currencyCode":"USD","inShoppingList":false}],"brandName":"Shurfine","offerName":"Worcestershire sauce - 10% off","description":"Since 1835, Lea & Perrins? has been the one authentic brand of Worcestershire Sauce. Aged in wooden casks for 18 months, Lea & Perrins uses only the finest ingredients sourced from around the world to produce a flavor unmatched for over 170 years.","shortDescription":"Worcestershire Sauce","legalDescription":"Limit of one coupon per person per visit. Cannot be combined with any other offer.","pictureUrl":"https://sprdeviceapisstaging.hana.ondemand.com/deviceapi/v1/rest/media/file/0011161147190.jpg","offerUrl":null,"currencySymbol":null,"currencyCode":null,"isCoupon":true,"isFavourite":false,"customValue1":null,"customValue2":null,"customValue3":null},{"id":"ada3c039-7e38-4586-b574-0cac8588a335-87320a30","offerType":"Money discount","value":1.00,"storeId":null,"isCashback":false,"isCounter":false,"isFreeItem":false,"isMoney":true,"isPercentage":false,"isPoint":false,"buyQuantity":0,"getQuantity":0,"validFromUtc":"1342328400000","validToUtc":"1405400400000","numberOfProductsInThisOffer":1,"offerProducts":[{"productId":"01e41d47-959b-435c-944a-ccd8a912f37d","productFamily":"Oil","brandName":"Shurfine","retailPrice":7.49,"currencySymbol":"$","currencyCode":"USD","inShoppingList":false}],"brandName":"Shurfine","offerName":"1$ Off Vegetable Oil","description":"Take 1$ off on vegetable oil, it's always good to save on essentials.","shortDescription":"Special Offer on Vegetable Oil","legalDescription":"Limit of one coupon per person per visit. Cannot be combined with any other offer.","pictureUrl":"https://sprdeviceapisstaging.hana.ondemand.com/deviceapi/v1/rest/media/file/0011161171034.jpg","offerUrl":null,"currencySymbol":"$","currencyCode":"USD","isCoupon":true,"isFavourite":false,"customValue1":null,"customValue2":null,"customValue3":null},{"id":"18d8ad7a-bb80-4db5-a576-e29027876dbd-87320a30","offerType":"Percentage discount","value":0.23,"storeId":null,"isCashback":false,"isCounter":false,"isFreeItem":false,"isMoney":false,"isPercentage":true,"isPoint":false,"buyQuantity":0,"getQuantity":0,"validFromUtc":"1342328400000","validToUtc":"1405400400000","numberOfProductsInThisOffer":5,"offerProducts":[{"productId":"8e303b2c-a635-4305-92ac-044011f26f28","productFamily":"Male","brandName":"Axe","retailPrice":25.00,"currencySymbol":"$","currencyCode":"USD","inShoppingList":false},{"productId":"b62bf90c-4c64-42db-98d4-66007d5a66f0","productFamily":"Male","brandName":"Axe","retailPrice":1.99,"currencySymbol":"$","currencyCode":"USD","inShoppingList":false},{"productId":"222206b6-0234-494f-ad0d-e12e773beba8","productFamily":"Male","brandName":"Axe","retailPrice":5.55,"currencySymbol":"$","currencyCode":"USD","inShoppingList":false},{"productId":"0d6504fe-a8dc-4770-b349-ae04cb62e0d6","productFamily":"Male","brandName":"Axe","retailPrice":5.00,"currencySymbol":"$","currencyCode":"USD","inShoppingList":false},{"productId":"a6f7ea63-8c51-4f40-8007-0959f0998e21","productFamily":"Liquid Soap","brandName":"Axe","retailPrice":7.29,"currencySymbol":"$","currencyCode":"USD","inShoppingList":false}],"brandName":"Axe","offerName":"Body Spray ","description":"Axe or Lynx (in the United Kingdom, the Republic of Ireland, Australia, and New Zealand) is a brand of male grooming products consisting of body sprays, deodorants, antiperspirants, shower gels and hair products.","shortDescription":"Save on AXE Products for Men","legalDescription":"Conditions apply","pictureUrl":"https://sprdeviceapisstaging.hana.ondemand.com/deviceapi/v1/rest/media/file/0011111010048.jpg","offerUrl":null,"currencySymbol":null,"currencyCode":null,"isCoupon":true,"isFavourite":false,"customValue1":null,"customValue2":null,"customValue3":null},{"id":"21a7b000-9529-4404-8f67-87b87e00340c-87320a30","offerType":"Cashback","value":2.00,"storeId":null,"isCashback":true,"isCounter":false,"isFreeItem":false,"isMoney":false,"isPercentage":false,"isPoint":false,"buyQuantity":0,"getQuantity":0,"validFromUtc":"1342328400000","validToUtc":"1405400400000","numberOfProductsInThisOffer":1,"offerProducts":[{"productId":"dd225ee5-d9b2-4d00-85e3-3f335611f63b","productFamily":"Pasta Prepared Mix","brandName":"Skinner","retailPrice":25.00,"currencySymbol":"$","currencyCode":"USD","inShoppingList":false}],"brandName":"Skinner","offerName":"Spaghetti instant cashback of 2$","description":"Get an instant 2$ cashback on spaghetti. You just need to register your product on the website.","shortDescription":"Spaghetti Instant Rebate","legalDescription":"Conditions apply","pictureUrl":"https://sprdeviceapisstaging.hana.ondemand.com/deviceapi/v1/rest/media/file/0012700122043.jpg","offerUrl":null,"currencySymbol":"$","currencyCode":"USD","isCoupon":false,"isFavourite":false,"customValue1":null,"customValue2":null,"customValue3":null},{"id":"00460d63-88b1-406a-893e-e6eaf634ae70-87320a30","offerType":"Free item","value":0.00,"storeId":null,"isCashback":false,"isCounter":false,"isFreeItem":true,"isMoney":false,"isPercentage":false,"isPoint":false,"buyQuantity":4,"getQuantity":5,"validFromUtc":"1342328400000","validToUtc":"1405400400000","numberOfProductsInThisOffer":1,"offerProducts":[{"productId":"3891ec44-0141-41bc-8afe-97252606e939","productFamily":"Dried Fruit","brandName":"Sun-Maid(R)","retailPrice":3.45,"currencySymbol":"$","currencyCode":"USD","inShoppingList":false}],"brandName":"Sun-Maid(R)","offerName":"Sunmaid Californian Raisins, buy 4 get 1 free","description":"Buy 4 packs of Sunmaid Californian raisins and get the 5th one for free","shortDescription":"California Raisins","legalDescription":"All packs have to be purchased on the same transaction. Limit of one redemption per client.","pictureUrl":"https://sprdeviceapisstaging.hana.ondemand.com/deviceapi/v1/rest/media/file/0041143029008.jpg","offerUrl":null,"currencySymbol":null,"currencyCode":null,"isCoupon":false,"isFavourite":false,"customValue1":null,"customValue2":null,"customValue3":null}],"moreOffers":false,"moreOffersURLPath":null}} Offer Count : 5
What now?
You should now be able to make all the other calls described in the SPM Device API documentation, they are all built using the same pattern.
The full documentation of the partner API is available here: https://help.sap.com/spm select the Device Services API Documentation
If you intend to work on Android or Java script then I'd recommend you try one of the following SDK samples that should make it easier for you to develop front end Apps using the Precision Marketing Device API:
SAP Precision Marketing Android SDK
SAP Precision Marketing Hybrid SDK
have fun with the trial, and send us feedback via the comments below or by writing toSAPprecisionmarketing-info@sap.com