The remote server returned an error: (401) Unauthorized errorHI,
Hi,
I’m trying to validate the postal code but getting “The remote server returned an error: (401) Unauthorized” error. I tried in your online api tool and it’s working.If I copied the Authorization header from your online tool to my post request method and then it’ working. I think some problem in getting the Authorization header. Here is code.
public ActionResult Index()
{
dynamic postcode = new JObject();
postcode.postal_code = "11144";
var contentAsString = JsonConvert.SerializeObject(postcode).ToString();
var header = urbItRequest.GetAuthorizationHeader("POST", "https://stage-retailer-api.urb-it.com/api/postalcode/validate", string.Empty);
var response = urbItRequest.DoRequest("POST" , "https://stage-retailer-api.urb-it.com/api/postalcode/validate", header, contentAsString);
return View();
}
public string GetAuthorizationHeader(string method, string url, string contentAsJson)
{
var digestBase64 = String.Empty;
if (String.IsNullOrWhiteSpace(contentAsJson))
{
var content = Encoding.UTF8.GetBytes(contentAsJson);
byte[] requestContentHash = MD5.Create().ComputeHash(content);
digestBase64 = Convert.ToBase64String(requestContentHash);
}
var timestamp = urbitConfig.GetTimestamp;
var nonce = urbitConfig.GetNonce;
var msgToSisgn = String.Format("{0}{1}{2}{3}{4}{5}",
urbitConfig.GetStoreId,
method.ToUpper(),
url.ToLower(),
timestamp,
nonce,
digestBase64);
var secretKeyByteArray = Convert.FromBase64String(urbitConfig.GetSharedSecret);
using (var hmac = new HMACSHA256(secretKeyByteArray))
{
byte[] signatureBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(msgToSisgn));
var requestSignatureBase64String = Convert.ToBase64String(signatureBytes);
return String.Format("UWA {0}:{1}:{2}:{3}",
urbitConfig.GetStoreId,
requestSignatureBase64String,
nonce,
timestamp );
}
}
public string DoRequest(string method, string uri, string header, string parameters = "")
{
string response = string.Empty;
using (var client = new WebClient())
{
client.Headers.Add(HttpRequestHeader.Authorization, header);
client.Headers.Add(HttpRequestHeader.Accept, string.Format("application/vnd.urb-it.se+json; version={0}", "1"));
client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=UTF-8");
response = client.UploadString(new Uri(uri), method.ToUpper(), parameters);
}
return response;
}
Regards
Nadeem
Solved!Posted in General by Nadeem