While posting to a external website, I received the following error. I changed the Request.ContentType to “text/xml”. Also added some retry logic
Error
Description: System.ServiceModel.ProtocolException: Unrecognized charSet ‘ISO-8859-1’ in contentType.
Solution
public string PostMerchantRequest(string requestXml)
{
const string artifactPrefix = "Method: PostMerchantRequest (string). ";
int retryCtr = 3;
string responseString = String.Empty;
log.WriteLine(artifactPrefix + "Constructing request to submit onto merchant");
string merchantUri = Constants.Merchant.URI;
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(merchantUri);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] postArray = encoding.GetBytes(requestXml);
Request.ContentType = "application/x-www-form-urlencoded";
Request.ContentLength = postArray.Length;
Request.Method = MessageTemplate.WebRequest.OperationType.POST;
Request.ContentType = "text/xml";
Exception commError = null;
while (retryCtr > 0 && String.IsNullOrEmpty(responseString))
{
try
{
Stream newStream = Request.GetRequestStream();
newStream.Write(postArray, 0, postArray.Length);
newStream.Close();
HttpWebResponse webResp = (HttpWebResponse) Request.GetResponse();
StreamReader responseStream = new StreamReader(webResp.GetResponseStream());
responseString = responseStream.ReadToEnd();
responseStream.Close();
webResp.Close();
}
catch (Exception ex)
{
commError = ex;
retryCtr--;
log.WriteLine(artifactPrefix + "Exception in communicating with merchant. Message = " + ex.Message,LogEntryOptions.Warn);
Thread.Sleep(3000);//Wait 3 seconds before next retry..
}
}
if ( (commError!=null) && (retryCtr == 0) && String.IsNullOrEmpty(responseString))
{
log.WriteLine(artifactPrefix + "Retry failed in submitting request to merchant." + LogEntryOptions.Error);
WebException webEx = new WebException(commError.Message,commError);
throw webEx;
}
log.WriteLine(artifactPrefix + "Merchant response received = " + responseString);
return responseString;
}
Happy coding !