我正在尝试在C#中创建一个方法,该方法与https://app.profitshare.ro/files/pdf/api_affiliate.pdf中提供的最后一个示例代码等效。
var apiUser = "bogdan";
var apiKey = "111222333444555666777888999";
var phUrl = "http://api.profitshare.ro/affiliate-links/?";
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var now = DateTime.Now;
var time = now.ToString("r");
var queryString = "";
var signatureString = $"POSTaffiliate-links/?{queryString}/{apiUser}{time}";
var request = new HttpRequestMessage(HttpMethod.Post, phUrl);
request.Headers.Add("Date", time);
request.Headers.Add("X-PS-Client", $"{apiUser}");
request.Headers.Add("X-PS-Accept", "json");
request.Headers.Add("X-PS-Auth", $"{HMAC_SHA1(signatureString, apiKey)}");
request.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
request.Content = new StringContent("{'name':'APIEmag','url':'www.emag.ro'}", Encoding.UTF8, "application/json");
var response = client.SendAsync(request).Result;
//--------------------------------------------------------------------------
static string HMAC_SHA1(string signatureString, string secretKey)
{
var enc = Encoding.ASCII;
HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));
hmac.Initialize();
byte[] buffer = enc.GetBytes(signatureString);
return BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();
}
我希望这段代码返回一个带有API返回的URL的JSON,但是每次都会收到BadRequest。我尝试了不同版本的useragent,但是结果是相同的。
最终使用RestClient(RestSharp)代替HttpClient,一切正常。