Signing URL – Java
This example illustrates how to sign request URL’s using .NET C#. In Java, you will need to download the following JAR to be able to execute the function.
Variables
| Name | Type | Summary |
|---|---|---|
| urlDomain | string (required) | URL of the service (ex: http://uk.shopping.yahooapis.com) |
| urlPath | string (required) | Path and query for the service (ex: /V2/search?query=ipod) |
| partner | string (required) | Affiliate Id |
| key | string (required) | Affiliate secret key |
Please note that your query must be encoded if you use characters with accents. In Java you can use URLEncoder in java.net.URLEncoder.
Sample Class
import java.security.DigestException;
import java.security.MessageDigest;
import org.apache.commons.codec.binary.Base64;
/**
* Function ySignUrl(String urlDomain, String urlPath, String partner, String key)
* Generates signed url from static url domain, url path, partner id and key
* @param urlDomain
* @param urlPath
* @param partner
* @param key
* @param URL_sig
* @param URL_ts
* @param URL_partner
* @return
* @throws Exception
*/
public static String ySignUrl(String urlDomain, String urlPath, String partner,String key) throws Exception{
String URL_sig = "hash";
String URL_ts = "timestamp";
String URL_partner = "aid";
String URLreturn = null;
// get the timestamp
long time = System.currentTimeMillis() / 1000;
// format URL
String URLtmp = urlPath + "&" + URL_ts + "=" + time + "&"
+ URL_partner + "=" + partner;
String tokken = null;
MessageDigest md = MessageDigest.getInstance("MD5");
try {
MessageDigest tc1 = (MessageDigest) md.clone();
String s = URLtmp + key;
byte[] toChapter1Digest = tc1.digest(s.getBytes("ISO-8859-1"));
byte[] b = Base64.encodeBase64(toChapter1Digest);
tokken = new String(b, "ISO-8859-1");
tokken = tokken.replace('+', '.').replace('/', '_').replace('=', '-');
} catch (CloneNotSupportedException cnse) {
throw new DigestException(
"couldn't make digest of partial content");
}
// format the concatained final URL
URLreturn = urlDomain + URLtmp + "&" + URL_sig + "=" + tokken;
return URLreturn;
}
Simply call the function to generate the appropriate URL:
import UrlSigner;
query = UrlSigner.ySignUrl("http://uk.shopping.yahooapis.com",
"/V2/search?query=ipod",
"123",
"PartnerKey");
System.out.println("Generated search query [" + query + "]");